Java 9 Stream API improvements

By | June 27, 2021

In this post, We will talk and learn about Java 9 Stream API improvements using an example

Java 9 added the new APIs for Stream.

Java Stream Iterate Method

  • A new overloaded iterate method is added in Java 9 stream interface. This function usually help us to iterate stream elements till the specified condition is true.
  • It takes three arguments, seed, hasNext, and next.

      public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> uo) 

Java Stream takeWhile() Method

  • Stream’s method takeWhile takes each element that matches its predicate. It stops when it gets the unmatched element. It returns a subset of elements that contains all matched elements, another part of the stream is discarded.

default Stream<T> takeWhile(Predicate<? super T> predicate)

This function returns if this stream is ordered, a stream to consist of the longest prefix of elements taken from this stream that match the given predicate.

Java Stream dropWhile() Method

  • The dropWhilemethod does the opposite of the takeWhile method

default Stream<T> dropWhile(Predicate<? super T> predicate)

Java 9 Stream ofNullable Method

  • Until Java 8, we cannot have null value in a stream. It would have caused NullPointerException.
  • In Java 9, the ofNullable function lets us create a single-element stream that holds a value if not null or is an empty stream otherwise.
  • Technically, ofNullable()is very similar to null condition check, when talking in the context of stream API.

public static<T> Stream<T> ofNullable(T t)

This method returns a sequential Stream containing a single element and if non-null otherwise returns an empty Stream.

Java9StreamImprovementsDemo.java

If you run ClientTest.java as Java Application then it will give the below output: 

That’s all about Java 9 Stream API improvements

You May Also Like:

Java 9 Jshell Tutorial
Java 9 private Methods in Interfaces
Java 9 Try with Resource Enhancement
Java 9 @SafeVarargs Annotation
Java 9 Collection Factory Methods

If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published.