How Java filter() Method Works in Background?


The Java filter() method allows us to strain elements of the stream based on the specified condition. It is a part of higher-order function that is used to apply a certain behavior on stream items. This method takes a predicate as an argument and returns a list of elements that match the predicate. But the question arises here is that how this filter() method works in the background. This article aims to explain this question through some example programs.

Working of filter() method in Background

Before going deep into the filter() method, let’s familiarize ourselves with I/O Streams. Itis an abstraction that is used while performing Input and Output operations in Java.Basically, the input streams are used to take input from sources like keyboard, disk files,etc. The output streams refer to the destination where data gets displayed or written.

Now come back to our discussion about filter() method. Earlier we coined the term‘Predicate’, you must be wondering what is this and what’s the purpose of using it with filter() method. The whole process of filtering revolves around this predicate. It is a functional interface passed as an argument to the filter() method and acts as a condition for filtering non-matching elements of stream. Originally, this method does not discard the non-matching elements. Rather, it generates a new stream of elements that contains only those elements that match the predicate condition.

Note that the filter() method is a stateless intermediate operation, which means it does not produce a result until we combine it with a terminal operation, such as count(), collect(), or forEach(). Here, stateless means it does not store any information about prior operations for further use.

There are two kinds of higher-order functions

  • Intermediate Operation − They process the elements of an input stream.

  • Terminal Operation − They trigger the intermediate operation to produce a nonstream result.

Syntax of filter()

filter(predicate);

Approach

  • Create a list using Arrays.asList() method to store a fixed-size list.

  • Now, use the filter() method along with stream() and forEach() to filter out the odd numbers only. Here, stream() specifies input in the form of stream and we will useforEach() to iterate and print the odd numbers.

  • Again, use the filter() method along with stream() and count() to print the count of odd numbers.

Example 1

The following example illustrates the use of filter() method.

import java.util.*;
public class Fltr {
   public static void main(String[] args) {
      // creating a list of numbers
      List<Integer> numbers = Arrays.asList(5, 21, 32, 14, 63, 19, 10);
      // printing all numbers in the list
      System.out.println("List of all numbers: " + numbers);
      System.out.println("List of odd numbers: ");
      // filtering only odd numbers from list
      numbers.stream()
         .filter(nums -> nums % 2 == 1)
         .forEach(System.out::println);
      System.out.println("Count of odd numbers: ");
      // printing the count of odd numbers
      System.out.println(numbers.stream()
         .filter(nums -> nums % 2 == 1)
         .count());
   }
}

Output

List of all numbers: [5, 21, 32, 14, 63, 19, 10]
List of odd numbers:
5
21
63
19
Count of odd numbers:
4

Approach

  • The first step is to import ‘java.util.function.Predicate’ to enable the use of Predicate class.

  • Define a fixed-size list.

  • Now, put the condition of printing odd numbers using an abstract method test() inside the Predicate definition.

  • Call the filter() method along with stream() and forEach() to filter out the odd numbers. Pass the instance of predicate class inside filter().

  • Again, call the filter() method along with stream() and count() to print the count of odd numbers.

Example 2

Let’s see another example of filter() method where we will use the Predicate class.

import java.util.*;
import java.util.function.Predicate;
public class Fltr {
   public static void main(String[] args) {
      // creating a list of numbers
      List<Integer> numbers = Arrays.asList(5, 21, 32, 14, 63, 19, 10);
      // printing all numbers in the list
      System.out.println("List of all numbers: " + numbers);
      System.out.println("List of odd numbers: ");
      // filtering only odd numbers from list
      Predicate<Integer> newNumbers = new Predicate<Integer>()
      {
         @Override
         public boolean test(Integer nums) {
            return nums % 2 == 1;
         }
      };
      numbers.stream()
         .filter(newNumbers)
         .forEach(System.out::println);
      System.out.println("Count of odd numbers: ");
      // printing the count of odd numbers
      System.out.println(numbers.stream()
         .filter(newNumbers)
         .count());
   }
}

Output

List of all numbers: [5, 21, 32, 14, 63, 19, 10]
List of odd numbers:
5
21
63
19
Count of odd numbers:
4

Conclusion

The filter() method works in the background by applying a Predicate to each element on demand. We have defined and explained the working of filter() method in detail through Java example programs. Also, we discovered the types of higher-order functions available in Java programming language.

Updated on: 21-Jul-2023

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements