Java 8 Streams

Posted on Posted in Uncategorized

Java 8 Streams

Streams provide another layer of abstraction on our collections of data that enable you to perform complex sets of actions on. The most powerful use of streams are chaining commands. For example, no longer do you need to perform a for loop to iterate over a collection of String.  Stream supports aggregate operations like filter, map, limit, reduce, find, match, and so on.

Filter

Filter is mainly used to eliminate elements based on  a criteria, the parameter it takes comes in the form of a Predicate  (takes in one parameter, returns boolean). Below we have a list of String and we only to print out those starting with ‘Good’, so below we chained to methods, filter(), and .forEach()

Collectors

In the previous example, we just passed the stream result to another function forEach to print out whatever was the result of the filter command. What do we do if we want to return a mutable list of what we have filtered? Collectors are exactly for that.

Continuing on the previous example, after we filtered, we can now return another list of Strings in filteredData object:

There are other powerful methods that Collectors can do, but we won’t dive in too much detail for that. For Example, you can comma-separate your results, pass them to another method, or even map them to maps. For more details check out this documentation: Collectors.

Limit

Limit is quite straight-forward, it just limits the number of elements inside your stream.  This method takes one parameter, just a long object that specifies the actual limit.

Sorted

Sorted is also quite straight-forward, it sorts the elements inside the stream. There are two possible implementation, no parameters, which assumes that object used in inside your stream have their own comparable implementation. The other takes a comparator parameter, with your implementation, here is both limit and sort in action:

Map

Map enables us to perform an operation on each individual element in the stream. Gone are the days for multiple for-loops when you start using lambdas. Check out this single line below which is based on the previous examples:

The example, will append my name on all the greeting, so it will be “Hello Mel”, “Bye Mel”, and so on. All this in just one line of code!

Leave a Reply