Java Stream filter() Method Tutorial

In this section, we will learn what the Stream filter() method is and how to use it in Java.

What is Java Stream filter() Method?

The Java Stream filter() method is used to put a filter on the elements of a stream and allow only those elements that match the predicate of the filter to pass.

Basically, this method takes a reference to another method, and inside that method we implement the conditions. Now the filter() method will call that method and pass each element of the stream as its argument. In this reference method, if the result was true, then the passed element will move forward to the next step through the stream. Otherwise, if the result of running the conditions on the target element of the stream resulted false, then that element will be removed from the stream.

Note: the method is an intermediate and lazy one.

Java filter() Method Syntax:

Stream<T> filter(Predicate<? super T> predicate)

filter() Method Parameters:

The method has one parameter and that is of type Predicate, which is a functional interface.

Basically, this method needs a reference to another method.

Here’s the signature of the reference method:

  • The method should take one argument of the same type as the elements of the target stream object.
  • The return value of this method is of type Boolean.

Inside the body of this reference method is the place where we define the instructions of the conditions to be executed on each element of the stream.

Note: we can create this reference method using either the lambda expression, or referencing an instance or static method.

filter() Method Return Value:

The return value of this method is a new stream.

filter() Method Exceptions:

The method might throw two exceptions and that is:

NullPointerException: We get this exception if the argument of this method is set to null.

ClassCastException: We get this exception if the datatype of the reference method is of incompatible type compared to the datatype of elements in the stream.

Example: using Stream filter() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(20,2,3,4,5,6,7,8,9,10,3,23,4,23,423,2,34,56,2,7,86,54,5);
        
        stream.filter(e→ e>50 ? True : false).forEach(e->System.out.println(e));
    }
}

Output:

423

56

86

54
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies