Java 9 Improved Stream API
Java 9 improved Stream API added some convenient methods to make stream processing easier and use collectors to write complex queries.
Java 9 added several methods to Stream: dropWhile, takeWhile, ofNullable, and added an overloaded method for the iterate method.
takeWhile method
Syntax
default Stream<T> takeWhile(Predicate<? super T> predicate)
The takeWhile() method takes a predicate as an argument and returns a subset of the given Stream until the predicate statement first returns false. If the first value does not satisfy the predicate condition, an empty Stream will be returned.
In an ordered Stream, takeWhile returns as many elements as possible from the beginning; in an unordered Stream, takeWhile returns a subset of elements from the beginning that meet the Predicate requirements.
Example
In the above example, the takeWhile method stops loop output when it encounters an empty string, and the execution output is:
abc
dropWhile method
Syntax
default Stream<T> dropWhile(Predicate<? super T> predicate)
The dropWhile method is the opposite of takeWhile. It takes a predicate as an argument and returns a subset of the given Stream only until the predicate statement first returns false.
Example
In the above example, the dropWhile method starts loop output when it encounters an empty string, and the execution output is:
ef
iterate method
Syntax
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
The method allows creating a sequential (possibly infinite) stream using an initial seed value, and iteratively applying the specified next method. When the specified hasNext predicate returns false, the iteration stops.
Example
Execution output is:
3 6 9
ofNullable method
Syntax
static <T> Stream<T> ofNullable(T t)
The ofNullable method can prevent NullPointerExceptions and avoid null values by checking the stream.
If the specified element is non-null, it gets an element and generates a single-element stream; if the element is null, it returns an empty stream.
Example
Execution output is:
1 0Other Extensions
Java 9 New Features