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.

Check out: takeWhile / dropWhile operations in Java 9 Stream
Iterate & ofNullable in Java 9 with Examples...!!! Share on X
In this tutorial, we are going to cover below topics:
- What is Iterate operation in Streams with example?
- 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
iterate(initialize section; next section)
Example with Java 8
Stream.iterate(5, count -> count+10 ).forEach(e -> System.out.println(e));
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
iterate(initialize section; predicate section(hasNext); next section)
Example with Java 9
IntStream.iterate(5, x -> x < 50, x -> x+5).forEach(e -> System.out.println(e));
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.
static<T> Stream<T> ofNullable(T t)
Example
import java.util.stream.Stream;
public class OfNullable_Java9_Example {
public static void main(String[] args) {
System.out.println("\nofNullable Example 1");
long count = Stream.ofNullable(5000).count();
System.out.println(count);
System.out.println("\nofNullable Example 2");
count = Stream.ofNullable(null).count();
System.out.println(count);
}
}
Output:
ofNullable Example 1 1 ofNullable Example 2 0
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...!!! Share on X
Do you like this Post? – then check my other helpful posts:
- Passing Function as a Parameter in another Method in Java 8
- Collection sorting using Lambda in Java 8
- Generate Prime numbers in Java 8