Filter a List using Lambda Expression and Stream in Java

Normally, before Java 8, when we want to filter a List, we will iterate through the List and base on the condition we want to filter, we can have a new List on demand.

For example, I have a List containing some student names as below:

Now, I want to filter above List to have a new List containing the student names only start with the letter “T”, then I will code as below:

Result:

Filter a List using Lambda Expression and Stream in Java

Since Java 8, we have another better way to do this by using Stream and Lambda Expression. Detail is: we will create new Stream object from our List object and use filter() method in this Stream object to filter.

The argument of filter() method is Predicate interface, a Functional interface, and this method is an intermediate operation. Then we need to add more method for a terminal operation to complete a Stream pipeline.

Here, after filtering, I will collect all the result into a List object by using terminal method collect() of Stream as below:

When running the code, the result will be same as above.

Filter a List using Lambda Expression and Stream in Java

 

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment