Thursday, September 28, 2017

Java 9 Streams: iterate() and ofNullable() methods

In Java 9, comes with a few good additions to the Stream API. For more information on the Java 8 Streams, go to the Java 8 Page. The following new methods were added to the Java 9 Stream API.
  1. dropWhile
  2. dropWhile
  3. iterate
  4. ofNullable
In this post we will take a look at the iterate() and ofNullable() methods.

Java 9 Stream iterate()

The new iterate() method in Java 9 is in addition to the Java 8 iterate() method. Both methods can be used to generate a stream of elements, but the new variation adds a predicate, which will determine when the iteration stops.
static <T> Stream<T> iterate​(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
In a way this performs similar to the for loop. In this example, we iterate over number starting from the seed (0) and incremenent by 1(n -> n + 1) with a predicate that will stop when n=10 (n->10).
Stream<Integer> stream2 = Stream.iterate(0, n -> n < 10, n -> n + 1);
stream2.forEach(x -> System.out.print(x + ", "));
System.out.println();

Output
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
The same functionality can be achieved by the Java 8 version of the iterator using the limit function as shown below.
Stream<Integer> stream1 = Stream.iterate(0, n -> n + 1).limit(10);
stream1.forEach(x -> System.out.print(x + ", "));

Output
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
However, the limit() function only allows to limit the the number of element, whereas the new iterate() the predicate can be anything. For example, in the following example when we change the increment by 2 instead of 1, the limit() will print upto 18, whereas the new iterate() function will print only till 8.
Stream<Integer> stream3 = Stream.iterate(0, n -> n + 2).limit(10);
stream3.forEach(x -> System.out.print(x + ", "));
System.out.println();

Stream<Integer> stream4 = Stream.iterate(0, n -> n < 10, n -> n + 2);
stream4.forEach(x -> System.out.print(x + ", "));
System.out.println();

Output
0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 
0, 2, 4, 6, 8, 

ofNullable Method

The Java 9 ofNullable() can be used to generate a stream consisting of a single element. From the Javadoc
Returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream.
The following code will create a stream consisting of exactly one element (1).
Stream<Integer> ofNullable1 = Stream.ofNullable(1);
ofNullable1.forEach(System.out::println);

Output
1
The following code returns an empty stream (not null, but an empty stream)
Stream<Integer> ofNullable2 = Stream.ofNullable(null);
ofNullable2.forEach(System.out::println);

Output

No comments:

Post a Comment

Popular Posts