Java 9 Stream Improvements

Java 9 Stream comes with some small useful improvements. In this tutorial, we’re gonna look at new added methods: iterate(), takeWhile()/dropWhile(), ofNullable().

Related Articles:
Lambda Expressions
Java 8 Streams

I. New Stream API
1. iterate

Old iterate() method has an initial value and a function for the next value.

This method causes problem when it returns an infinite sequential ordered Stream. For example, if we wanna create a sequence, next number is double previous one. We also need to limit the value of number by 20.
So we catch an idea that iterate() and filter() method can be used like this:

If we run this code, there’s a big problem: The program will never terminate. filter() has no idea about increment of sequence.

Java 9 Stream iterate() method adds a predicate as its second argument that checks condition to continue or not:

Now we can rewrite the code simply as below:

The result is:

2. takeWhile

Now we look at how Stream takeWhile() method behaves towards ordered Stream and unordered Stream.

– If the stream is ordered, it returns a stream consisting of the longest prefix of elements that match the given predicate. For example:

Longest prefix is the sequence of elements that match the given predicate, from the first element of this stream (if it matches the predicate) to the last element in chain. We call it “longest” because the stream is ordered, it is definitely longest.

– If the stream is unordered, it returns a stream consisting of a subset of elements that match the given predicate. For example:

Subset is the set of some elements that match the given predicate including first element of the stream (if it matches the predicate). In the example, (2, 3) is the longest sequence, but (1) is the true subset.

3. dropWhile

dropWhile() is the opposite of takeWhile().

– If the stream is ordered, it returns a stream consisting of the remaining elements after dropping the longest prefix that match the given predicate. For example:

– If the stream is unordered, it returns a stream consisting of the remaining elements after dropping the subset that match the given predicate. For example:

4. ofNullable

Sometimes we wanna add an element to a Stream, but this element may be a null, and we don’t wanna get that null value for our stream.

Java 9 provides new ofNullable() method for Stream that helps us add element without checking if it is null:

We check the method with a simple code:

In early approach, to add an element, we make a null check in the code, it looks inelegant. For example:

With new API, we can write in elegant way like this:

II. Source Code

Run the code, this is result:


Related Posts


Got Something To Say:

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

*