Wednesday, July 3, 2024
HomeLanguagesJavaImplement Filter Function using Reduce in Java 8 Streams

Implement Filter Function using Reduce in Java 8 Streams

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]

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments