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<Integer> 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<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); double sum = 0; Iterator<Integer> 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<Integer> 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<Integer> 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, https:. All rights reserved. On republishing this post, you must provide link to original post