What is the Stream filter() method in Java?

Overview

The Stream filter() method is used to select elements as per the Predicate passed as argument. The Predicate is a functional interface and can be used as an assignment target for a lambda expression or method reference.

This answer explains how the Stream filter() method works with an example.

Syntax

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

Parameters

  • predicate: This a non-interfering, stateless predicate to apply to each element to determine if it should be included

Return value

It returns a new stream consisting of the elements that match the given predicate.

Example

The following example shows how to use Stream filter() method with a custom Predicate.

Main.java
Person.java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
// Adding elements in the list
list.add(new Person("John", 32, 'M'));
list.add(new Person("Jennie", 30, 'F'));
list.add(new Person("Mike", 35, 'M'));
list.add(new Person("Teddy", 38, 'M'));
list.add(new Person("Alice", 40, 'F'));
// Instantiating the Predicate interface
// referring isMale() method of Person class
// as its functional interface method
Predicate<Person> male = Person::isMale;
// Using Stream filter() to find male persons
list.stream()
.filter(male)
.forEach(System.out::println);
}
}

Explanation

Person.java

  • Line 1–4: We create a class named Person, which has three fields—name, age, and gender.
  • Line 4–6: We define a constructor to instantiate Person object.
  • Line 12–25: We define the getter methods of each of the fields.
  • Line 27–34: We override the toString() method to print the Person object in a more user friendly manner.
  • Line 37–42: We define the isMale method of the Person class. Note that isMale() method is a static method.

Main.java

  • Line 3: We create a class named Main.
  • Line 4: We declare the main() method.
  • Line 5: We create an ArrayList of Person objects.
  • Line 8–12: We add five Person objects to the ArrayList created in Line 5.
  • Line 18: We declare a reference variable male of type Predicate interface, which refers to the isMale() method of the Person class.
  • Line 21–22: First, we obtain a stream from the list using the stream() method. Then we use the filter() method with the Predicate object to filter all Person objects in the list whose gender is male.
  • Line 23: We print all the elements in the filtered stream using the forEach() method.

Free Resources