How to sum a list of integers with java streams?
You can use the reduce()
operation in the Java Streams API to sum the elements of a list of integers. The reduce()
operation combines all the elements of the stream into a single result, using a specified accumulator function.
Here's an example of how you can use reduce()
to sum the elements of a list of integers:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int sum = list.stream()
.reduce(0, (a, b) -> a + b);
System.out.println(sum); // prints 15
In this example, the accumulator function is a lambda expression that takes two arguments, a
and b
, and returns the sum of a
and b
. The initial value of the accumulator is 0.
You can also use the sum()
method of the IntStream
class to sum the elements of a list of integers. Here's an example of how you can use IntStream.sum()
to sum the elements of a list of integers:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int sum = list.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum); // prints 15
I hope this helps! Let me know if you have any questions.