Easy Way to Filter Collection Using Java Stream

I’ve been a huge fan of Linq in C# (we are going to talk about Linq someday). In Java, there is something similar to Linq which is called Stream. Because most of my current works today involving Java, so I guess I’m going to talk about Java Stream first.

What is Stream

Introduced in Java 8, it’s a new abstract layer that gives us the ability to process data in a declarative way. This feature was built by the availability of Lambda expressions which also introduced in Java 8. Stream represents a sequence of objects that we able to apply aggregate operations. Some of those operations including filter, map, flatmap, limit, reduce, find, match, and so on. By using Stream, we don’t have to handle those aggregate operations on our own which will save us time.

Hands On

Explanation without an example would be useless. So, let’s say we have a list of posts called posts which contain a list of articles from a website. Then, let’s say we want to get articles that the author is “Haydar”. Usually, we would do something like this.

In this case, it still looks simple. But, what if the condition is getting complex. That would make the code looks cluttered. Here is where the Stream comes to the rescue!

By using Stream, we can use something like this.

Much simpler, right? We don’t have to iterate manually and it is more readable. The code on line 3 is actually just converting the Java List into a Stream object, we can do the aggregate operations if we already convert it into a Stream object. Then, the filter is on line 4 which basically we tell it to only fetch post that has the author with name “Haydar”. After that, the line 5 is basically returned back the Stream object as a list.

Wrap Up

At this point, it seems that it’s not optimizing the number of characters that we need to write. Because the example operation is just way to easy in both ways. Next, we will visit several examples of Java Stream usages that will enable a better way to handling aggregate operations. Thank you for reading.




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Haydar Ali Ismail

Haydar Ali Ismail

Half Data Engineer, Half Software Engineer