Sum of ArrayList java

In this article, we will see different options to calculate sum or average of an ArrayList.

Using Looping structures

Here is we are using an enhanced for loop to find the average of given arraylist of integers. However, any looping construct like while, do..while, for loop etc can be used.

package com.test; import java.util.Arrays; import java.util.List; public class ArrayListOperations { public static void main[String[] args] { List list = Arrays.asList[1, 2, 3, 4, 5, 6, 7, 8]; double sum = 0; for [int i : list] { sum += i; } double average = sum / list.size[]; System.out.println["Average = " + average]; } }

Output :
Average = 4.5

You could also use an Iterator or ListIterator for the same.

Here is the code :

List list = Arrays.asList[1, 2, 3, 4, 5, 6, 7, 8]; double sum = 0; Iterator iter1 = list.iterator[]; while [iter1.hasNext[]] { sum += iter1.next[]; } double average = sum / list.size[]; System.out.println["Average = " + average];

Output :

Average = 4.5

Refer more on the iterators in this article :

Iterating a collection using Iterator, ListIterator, ForEach and Spliterator

Using Java 8 Stream

List list = Arrays.asList[1, 2, 3, 4, 5, 6, 7, 8]; OptionalDouble avg = list.stream[].mapToDouble[i -> i].average[]; System.out.println["Average = " + avg.getAsDouble[]];

Output :

Average = 4.5

Using Java 8 IntStream average[] method

List list = Arrays.asList[1, 2, 3, 4, 5, 6, 7, 8]; OptionalDouble avg = list.stream[].mapToInt[Integer::intValue].average[]; System.out.println["Average = " + avg.getAsDouble[]];

Refer following article to know more about other IntSream operations :

Java 8 IntStream operations with examples

© 2017, . All rights reserved. On republishing this post, you must provide link to original post

Share this article :

  • Click to share on LinkedIn [Opens in new window]
  • Click to share on Facebook [Opens in new window]
  • Click to share on Twitter [Opens in new window]
  • More
  • Click to share on Pinterest [Opens in new window]
  • Click to share on Flipboard [Opens in new window]
  • Click to share on Tumblr [Opens in new window]
  • Click to share on Reddit [Opens in new window]
  • Click to share on Pocket [Opens in new window]

Related

Popular Articles you may like :

  • Java 8 Interview Questions
  • RESTful CRUD operations using Jersey and Hibernate
  • Frequently asked Java Programming Interview questions on Strings

Video liên quan

Chủ Đề