The filter() method is the standard way to select elements from a stream. However, the same behavior can also be achieved using the reduce() method by accumulating only the elements that satisfy a given condition. This approach helps in understanding how stream reduction works internally and demonstrates the flexibility of the reduce() operation.
- Uses reduce() to accumulate only the elements that match a condition.
- Helps understand how reduction can be used beyond numeric operations.
- Mainly used for learning purposes, as filter() is more readable and efficient for filtering.
How Does Filter Using Reduce Work?
The reduce() method processes every element in the stream one by one. During each iteration, it checks whether the current element satisfies the filtering condition. If the condition evaluates to true, the element is added to the result list. Otherwise, it is ignored. After processing all elements, the accumulated list contains only the filtered elements.
Given a list of Integers, PRINT a list of Even Numbers present in the list using Reduce function in Java 8 Streams.
INPUT : [1, 2, 3, 4, 5,6, 7]
OUTPUT : [2, 4, 6]
INPUT : [1, 7, 9]
OUTPUT : []
Example:
import java.io.*;
import java.util.*;
import java.util.stream.*;
class GFG {
public static void main(String[] args)
{
List<Integer> arr = List.of(1, 2, 3, 4, 5, 6, 7);
List<Integer> even
= arr.stream().reduce(new ArrayList<Integer>(),
(a, b)
-> {
if (b % 2 == 0)
a.add(b);
return a;
},
(a, b) -> {
a.addAll(b);
return a;
});
System.out.println(even);
}
}
Output
[2, 4, 6]
Explanation: In this example, reduce() is used to implement filtering by accumulating only the elements that satisfy the given condition. An empty ArrayList acts as the accumulator, and each even number encountered in the stream is added to it. After processing all elements, the accumulated list contains only the filtered even numbers, which are then printed.