Java 9 Improved Stream API

Java 9 新特性Java 9 New Features

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

import java.util.stream.Stream; public class Tester { public static void main(String[] args) { Stream.of("a","b","c","","e","f").takeWhile(s->!s.isEmpty()) .forEach(System.out::print); } }

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

import java.util.stream.Stream; public class Tester { public static void main(String[] args) { Stream.of("a","b","c","","e","f").dropWhile(s-> !s.isEmpty()) .forEach(System.out::print); } }

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

java.util.stream.IntStream; public class Tester { public static void main(String[] args) { IntStream.iterate(3, x -> x < 10, x -> x+ 3).forEach(System.out::println); } }

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

import java.util.stream.Stream; public class Tester { public static void main(String[] args) { long count = Stream.ofNullable(100).count(); System.out.println(count); count = Stream.ofNullable(null).count(); System.out.println(count); } }

Execution output is:

1
0

Java 9 新特性Java 9 New Features

Other Extensions