Using Stream API filter and findFirst() methods Using Stream API filter and findAny() methods
From Java 8 onwards, you can use Java Stream API to filter elements from a Collection like List,
and in this approach we are going use
In order to follow below example, create a class called
Let's write a program to find the first person from list whose age is greater than 30.
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 . This essentially pass everyPerson object from the list and check whether predicate condition is passed. -
Then we are calling
findFirst() , when the first match of predicate condition occurred on a Person object, then it returns and exits there. This method returnsOptional<Person> . -
Optional is kind of a container class which holds an Object with some utility methods, you can check
isPresent() method on Optional, if it present you can retrieve the underlying object usingget() on Optional. See this article to know more onOptional .
When you run the above program, you will get the below output.
This approach is same as above except that in place of
When you run the above program, you will get the below output. Please note that the output may not be same in your case and may vary.
Above example complete source code can be found here on
Similar Articles
-
Filter and collect elements 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