Java 8 Stream filter examples

Previous
Next
In this post,  we are going to see about java 8 stream filter example.
You can convert list or array to stream very easily and perform various operations on top of it.Java 8 Stream provides various methods such as map,  filter, reduce etc.
Let’s see more about Java 8 Stream filter method.

Java 8 Stream filter :

As name suggests,  filter method is used to filter stream on basis of criterion. You can pass lambda expression to filter method but it should always return a boolean value. We have already seen how to pass Predicate object to filter method to filter a collection.
Lets understand more with help of example: 
Lets say you have student class as below:

Lets say you have list of student objects in studentList and you need to filter all male students.
You can do it with the help of Stream with below code:

Here we have used Stream’s filter method to filter list and then collect the result to another list with Collectors.toList().

Java 8 filter,findAny or orElse method:

You can use stream’s filter method to filter list and use findAny and orElse method based on conditions.
For example:You want to filter Student with name “John”, if you do not find it in the list then return null.

Lets create a main class as below:

When you run above program, you will get below output:

Let me know if you need more examples for Stream’s filter method.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog