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...!!! Click To Tweet
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
1 | iterate(initialize section; next section) |
Example with Java 8
1 | 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
1 | iterate(initialize section; predicate section(hasNext); next section) |
Example with Java 9
1 | IntStream.iterate(5, x -> x < 50, x -> x+5).forEach(e -> System.out.println(e)); |
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.
1 | static<T> Stream<T> ofNullable(T t) |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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:
1 2 3 4 5 | 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...!!! Click To Tweet
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