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.
Stream<T> filter(Predicate<? super T> predicate)
predicate
: This a non-interfering, stateless predicate to apply to each element to determine if it should be includedIt returns a new stream consisting of the elements that match the given predicate
.
The following example shows how to use Stream filter()
method with a custom Predicate
.
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);}}
Person.java
Person
, which has three fields—name
, age
, and gender
. Person
object.toString()
method to print the Person
object in a more user friendly manner.isMale
method of the Person
class. Note that isMale()
method is a static
method.Main.java
Main
.main()
method.ArrayList
of Person
objects.Person
objects to the ArrayList
created in Line 5.male
of type Predicate
interface, which refers to the isMale()
method of the Person
class. 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.forEach()
method.