Site icon Java Guidance

How to sum even numbers with Reduce in java ?

How to sum even numbers with Reduce in java

How to sum even numbers with Reduce in java

How to sum even numbers with Reduce in java

In this Java code snippet, a list of integers named `numbers` is created with values 2, 4, 6, 8, and 10. Using Java 8 streams, the code calculates the sum of even numbers from the `numbers` list.

The `filter` operation selects only even integers by checking the remainder of division by 2. The `reduce` operation then adds these even numbers together, starting with an initial value of 0, using the `Integer::sum` method reference.

The result stored in `sumOfEvens` is the sum of the even integers in the list.


List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 10);
int sumOfEvens = numbers.stream()
.filter(n -> n % 2 == 0)
.reduce(0, Integer::sum);

Exit mobile version