Java 9 introduced 4 new stream operations ie. takeWhile, dropWhile, iterate & ofNullable. These are some of the most useful features as part of stream introduced in Java 9. We have already covered takeWhile & dropWhile in this post. Now, in this tutorial, we are going to learn about rest of the two operations i.e Iterate & ofNullable.  

Iterate_ofNullable_Java9_FeaturedImage_Techndeck

Check out: takeWhile / dropWhile operations in Java 9 Stream

Iterate & ofNullable in Java 9 with Examples...!!! Click To Tweet

In this tutorial, we are going to cover below topics:

  1. What is Iterate operation in Streams with example?
  2. What is ofNullable operation in Streams with example?

1. Iterate operation in Streams

Before Java 9

Streams already has this iterate method with two arguments. One is the initializer of the iteration, which is called as a ‘seed’, and the second argument is the ‘function’ to be applied to the first element to produce the new element. But if you notice, there is a problem with that. Problem is that there is no termination of the loop. 

Javadoc syntax

Example with Java 8  

If you notice above, there is no stop, it will continue to print forever. 

Now Since Java 9

Java 9 holds this method but with some alteration to it. To solve the termination problem, one more argument has been added i.e. predicate

Javadoc syntax

Example with Java 9

If you notice the above code now, there is a predicate in the middle argument which forces the iteration to stop once the condition isn’t matching the prediate.

2. ofNullable operation in Streams

Returns a sequential Stream containing a single element, if non-null, otherwise returns an empty. Java 9 introduced to avoid NullPointerExceptions and to avoid having null checks of streams. The main objective is to return empty Optionals if the value is null.

Javadoc syntax

Example

Output:

Iterate & ofNullable are truly useful addition as part of Streams in Java 9 and can serve variety of purposes. I hope above examples could help you to get better idea on how to implement it.

Iterate & ofNullable in Java 9 with Examples...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References: