How to use Java 8 Streams Filter in Java Collections

How to use Java 8 Streams Filter in Java Collections:- 

In this article, we are going to discuss how to use Java 8 Streams Filter effectively in java collections.We are going to demonstrate examples of Java 8 streams filter using fliter(),collect(),distinct(),limit(),findany().Lets try and understand with following use case.




we are going to create a list of Users and perform some operations such as finding Users on basis of salary.Let’s See how we will do it prior to Java 8.

Create a user Class:-

Using stream filter() and map():-

We are going to implement a simple use case to find users whose age is greater than 20 from the above list and try and understand the core usage of Java 8 streams filter.

In Java 7:-

In Java8:-

Output:-

So looking at both the code you might wonder what is the big deal in Java 8 Streams, just a syntactical difference? Now think about Sorting and getting top 3 elements or getting first three. The Java 7 code would ask you to add more logical operators or conditional blocks.


We are coding using  Java 8 streams filter here.The main advantage of using this syntax is we are coding in a declarative way.We are declaring what we want to achieve instead of implementing a complex control flow statement.There are a lot of other advantages as well which we are not going to cover here.

One Point to highlight is we are using,map(User::getName) , so map takes a functional interface as the parameter in Java8 Streams.we can also use a functional method as well:-

output:-

Using Java 8  streams filter() , distinct() and limit():-

The Use case we target here is to find first three different users whose age is greater than 20.

Java 8:-

Output:-

We are using  Java 8 Streams filter with.distinct() and limit(3)

 

Using Java 8  streams filter() , findAny() and orElse():-

The Use case we target here is to find any single user whose age is greater than 20 and name is John.

Just trying to demonstrate how to add multiple conditions inside Java 8 streams filter.

Java 8:-

Output:-

Leave a Reply

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