
1. Overview
In this article, we will learn to sum all the elements in the ArrayList using Java 8. To learn more about Java streams, refer to these articles.
2. Sum all the elements in the ArrayList using Java 8
A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation, such as finding the sum of a set of numbers. The streams classes have multiple specialized reduction forms such as sum()
, max()
, or count()
.
So, we can use this sum()
reduction operation to get the sum of all the elements in the ArrayList
.
The sum
operation returns the sum of elements in this stream. This is a special case of a reduction and is equivalent to:
return reduce(0, Integer::sum);
This is a terminal operation. The Terminal operations may traverse the stream to produce a result. After the terminal operation is performed, the stream pipeline is considered consumed, and can no longer be used.
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5); List<Long> longs = Arrays.asList(1L, 2L, 3L, 4L, 5L); List<Double> doubles = Arrays.asList(1.2d, 2.3d, 3.0d, 4.0d, 5.0d); List<Float> floats = Arrays.asList(1.3f, 2.2f, 3.0f, 4.0f, 5.0f); long intSum = ints.stream() .mapToLong(Integer::longValue) .sum(); long longSum = longs.stream() .mapToLong(Long::longValue) .sum(); double doublesSum = doubles.stream() .mapToDouble(Double::doubleValue) .sum(); double floatsSum = floats.stream() .mapToDouble(Float::doubleValue) .sum(); System.out.println(String.format( "Integers: %s, Longs: %s, Doubles: %s, Floats: %s", intSum, longSum, doublesSum, floatsSum));
3. Alternative ways to sum all elements in the ArrayList
3.1. We can implement using the simple sequential loops, as in:
int sum = 0; for (int x : numbers) { sum += x; }
3.2. We can use the general-purpose reduce
operation directly. These reduction operations can run safely in parallel with almost no modification:
int sum = numbers.stream().reduce(0, (x,y) -> x+y); or int sum = numbers.stream().reduce(0, Integer::sum); // parallel streams int sum = numbers.parallelStream().reduce(0, Integer::sum);
Parallel streams enable us to execute code in parallel on separate cores. The final result is the combination of each individual outcome. However, the order of execution is out of our control. It may change every time we run the program:
4. Conclusion
To sum up, we have learned to sum all the elements in the list using Java 8. To learn more about Java streams, refer to these articles.