English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java 9 The improved Stream API adds some convenient methods to make stream processing easier and to write complex queries with collectors.
Java 9 Several methods have been added for Stream: dropWhile, takeWhile, ofNullable, and an overloaded method has been added for the iterate method.
Syntax
default Stream<T> takeWhile(Predicate<? super T> predicate)
The takeWhile() method uses an assertion as a parameter and returns a subset of the given Stream until the assertion statement returns false for the first time. If the first value does not meet the assertion condition, an empty Stream will be returned.
The takeWhile() method returns as many elements as possible from the beginning in an ordered Stream; in an unordered Stream, takeWhile returns a subset of elements that meet the Predicate requirements from the beginning.
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); } }
The above example of the takeWhile method stops looping output when encountering an empty string, and the executed output result is:
abc
Syntax
default Stream<T> dropWhile(Predicate<? super T> predicate)
The dropWhile method and takeWhile have opposite effects. They use an assertion as a parameter and return a subset of the given Stream until the assertion statement returns false for the first time.
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); } }
The above example of the dropWhile method starts looping output when encountering an empty string, and the executed output result is:
ef
Syntax
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
The method allows the creation of sequential (possibly infinite) streams using an initial seed value and iteratively applying the specified next method. Iteration stops when the specified hasNext predicate returns false.
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); } }
The execution output result is:
3 6 9
Syntax
static <T> Stream<T> ofNullable(T t)
The ofNullable method can prevent NullPointerExceptions exceptions, and can avoid null values by checking the stream.
If the specified element is non-null, it retrieves an element and generates a single-element stream; if the element is null, it returns an empty stream.
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); } }
The execution output result is:
1 0