82
Java 9 Stream API Improvement
In Java 9, Stream API has improved and new methods are added to the Stream interface. These methods are tabled below.
Modifier and Type | Method | Description |
---|---|---|
default Stream<T> | takeWhile(Predicate<? super T> predicate) | It returns, if this stream is ordered, a stream consisting of the longest prefix of elements taken from this stream that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of a subset of elements taken from this stream that match the given predicate. |
default Stream<T> | dropWhile(Predicate<? super T> predicate) | It returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate. |
static <T> Stream<T> | ofNullable(T t) | It returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream. |
static <T> Stream<T> | iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) | It returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying the given hasNext predicate. The stream terminates as soon as the hasNext predicate returns false. |
Java Stream takeWhile() Method
Stream takeWhile method takes each element that matches its predicate. It stops when it get unmatched element. It returns a subset of elements that contains all matched elements, other part of stream is discarded.
Java Stream takeWhile() Method Example 1
In this example, we have a list of integers and picks up even values by using takewhile method.
This example returns an empty list because it fails at first list element, and takewhile stops here.
Output:
[]
Java Stream takeWhile() Method Example 2