Open In App

Implement Filter Function using Reduce in Java 8 Streams

Last Updated : 21 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Many times, we need to perform operations where a stream reduces to a single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements. reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and the second argument is the current stream element. In this article, we are going to Implement the Filter Function using Reduce in Java 8 Streams.

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 : []

Recommended: Please try your approach on {IDE} first, before moving on to the solutiion

The idea used here is that we know a reduce function helps in summing numbers, concatenating strings, etc., or in general, accumulating objects. So as an accumulator we have an array that is initially empty and when an element satisfies the condition, it gets added to the array.

Java




/*package whatever //do not write package name here */
  
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]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads