×
☰ See All Chapters

Java 9 Stream API Improvements

Java 9 has added the following four useful new methods to java.util.Stream interface.

Modifier and Type

Method

Description

default Stream<T>

takeWhile(Predicate<? super T> predicate)

Predicate will be evaluated against the element from the stream. If predicate evaluates to true it will be collected, if predicate evaluates to false, it stops processing further (it stops taking elements further). takeWhile continues process the stream till the predicate is evaluated to true. Once predicate is evaluated to false it stops. All the elements which evaluates to true till then will be collected.

default Stream<T>

dropWhile(Predicate<? super T> predicate)

Predicate will be evaluated against the element from the stream. If predicate evaluates to true it will be dropped, if predicate evaluates to false, it stops processing further (it stops dropping elements further, so it takes all rest of the elements). dropWhile continues process the stream till the predicate is evaluated to true. Once predicate is evaluated to false it stops. All the elements which evaluates to true till then will be dropped and rest of the elements will be taken.

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.

 

takeWhile

dropWhile

ofNullable

iterate


All Chapters
Author