Java 8 Stream filter examples

Java 8 Stream filter
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 expressions 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:

Male students are :[Student [id=1, name=Arpit, gender=M, age=19], Student [id=2, name=John, gender=M, age=17], Student [id=4, name=Martin, gender=M, age=21]] Student with Name john :Student [id=2, name=John, gender=M, age=17]

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

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *