Using Stream API filter and collect methods
From Java 8 onwards, you can use Java Stream API and filter elements from a Collection like List.
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