Learn how to find sum of even numbers in Java 8 without using the sum() method. Use Stream API, filter() , and reduce() to calculate the result with practical examples.
Code Explanation (Point Wise)
• Arrays.asList() converts array elements into a List.
• stream() creates a stream from the list.
• filter(num -> num % 2 == 0) selects only even numbers.
• reduce(0, Integer::sum) adds all even numbers.
• doubleValue() converts the Integer result into Double.
• System.out.println() displays the final sum.
import java.util.Arrays;
import java.util.List;
public class ListQ {
public static void main(String[] args) {
List numbers =
Arrays.asList(1, 2, 3, 4, 5, 6, 1, 2, 3);
Double sum = numbers.stream()
.filter(num -> num % 2 == 0)
.reduce(0, Integer::sum)
.doubleValue();
System.out.println("Sum of even numbers without sum() method: " + sum);
}
}
Output :
Sum of even numbers without sum() method: 14.0
Java 8 Program to Find Sum of Even Numbers
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SumOfEvenNumbers {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 1, 2, 3);
int sum = numbers.stream()
.filter(num -> num % 2 == 0)
.collect(Collectors.summingInt(Integer::intValue));
System.out.println("Sum of even numbers: " + sum);
}
}
Output :
Sum of even numbers: 14
FAQ
What is the reduce() method in Java 8?
The reduce() method combines stream elements into a single result by repeatedly applying an accumulator function.
How do you find the sum of even numbers without using sum()?
Filter even numbers using filter() and then use reduce() to add them together.
Which is better: reduce() or sum()?
For numeric streams, sum() is simpler. However, reduce() offers more flexibility for custom aggregation operations.
Can reduce() be used for multiplication?
Yes, reduce() can perform addition, multiplication, concatenation, and many other aggregation operations.