Collectors
is a utility class that provides various implementations of reduction operations, such as grouping elements, adding elements to different collections, summarizing elements according to various criteria, and so on. The other functionalities in the Collectors
class are usually used as the final operation on streams.
filtering()
is a static method of the Collectors
class, which is used to return a Collector
that filters the input elements according to a given predicate and accumulates the elements for which the predicate returns True
. This method is generally used in multi-level reduction operations. For example, given a list of persons with their names and ages, we can get a list of the ages of the persons who are older than 30 for each different person name.
The filtering
method is defined in the Collectors
class. The Collectors
class is defined in the java.util.stream
package. To import the Collectors
class, we check the following import statement:
import java.util.stream.Collectors;
public static <T, A, R> Collector<T, ?, R> filtering(Predicate<? super T> predicate, Collector<? super T, A, R> downstream)
Predicate<? super T> predicate
: This is the predicate function that is used to filter the elements.Collector<? super T, A, R> downstream
: This is the Collector
that is applied on the filtering result.This method returns a Collector
that applies the predicate function to the input items and passes the filtered results to the downstream Collector
.
import java.util.*;import java.util.stream.Collectors;import java.util.stream.Stream;class Person{private String name;private int age;public Person(String name, int age) {setName(name);setAge(age);}void setName(String name){this.name = name;}void setAge(int age){this.age = age;}String getName(){return name;}int getAge(){return age;}@Overridepublic String toString() {return "Person{" +"name='" + getName() + '\'' +", age=" + getAge() +'}';}}public class main {public static void main(String[] args) {List<Person> personList = Arrays.asList(new Person("adam", 34), new Person("bob", 43),new Person("mary", 84), new Person("john", 12), new Person("kim", 22));System.out.println("List of persons - " + personList);Stream<Person> personStream = personList.stream();List<Person> result = personStream.collect(Collectors.filtering(objPerson -> objPerson.getAge() > 30, Collectors.toList()));System.out.println("Filtering result - " + result);}}
Person
class with name and age as the class’ attributes.Person
objects called personList
.personList
to the console.personList
called personStream
, using the list interface’s stream()
.result
. We achieve this with the help of the Collectors.filtering()
method.