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 listlist.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 methodPredicate<Person> male = Person::isMale;// Using Stream filter() to find male personslist.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, andgender. - Line 4–6: We define a constructor to instantiate
Personobject. - Line 12–25: We define the getter methods of each of the fields.
- Line 27–34: We override the
toString()method to print thePersonobject in a more user friendly manner. - Line 37–42: We define the
isMalemethod of thePersonclass. Note thatisMale()method is astaticmethod.
Main.java
- Line 3: We create a class named
Main. - Line 4: We declare the
main()method. - Line 5: We create an
ArrayListofPersonobjects. - Line 8–12: We add five
Personobjects to theArrayListcreated in Line 5. - Line 18: We declare a reference variable
maleof typePredicateinterface, which refers to theisMale()method of thePersonclass. - Line 21–22: First, we obtain a
streamfrom the list using thestream()method. Then we use thefilter()method with thePredicateobject to filter allPersonobjects in the list whose gender is male. - Line 23: We print all the elements in the filtered stream using the
forEach()method.