Using Stream API filter and collect methods
Filtering means selecting only those elements from a list that satisfy a condition — keeping every person older than 30, every order with a value above $100, every string starting with a specific prefix. The result is a new, smaller list; the original list is unchanged. Before Java 8, this required a loop, an
The pattern is: call
In order to follow below example, create a class called
Let's write a program to filter Person(s) with age greater than 30, but less than 40.
Explanation of above code:
-
First we called
stream() method onList<Person> that returns aStream<Person> objects. -
Then on the
Stream object, we calledfilter() method with a predicateperson.getAge() >30 && person.getAge() >40 . This essentially pass everyPerson object from the list and check whether predicate condition is passed. - Finally, collecting the result into a List.
When you run the above program, you will get the below output.
AFTER filter : [[name : Person B , age : 32], [name : Person D , age : 39]]
Above example complete source code can be found here on
Similar Articles
-
Filter and find an element from a List using Java Stream API (from Java 8 onwards) -
How to remove elements from a List -
How to remove elements from a List while iterating -
How to loop through elements of List in different ways