📜  Java9 Stream AP

📅  最后修改于: 2020-10-14 00:49:20             🧑  作者: Mango

Java 9 Stream API改进

在Java 9中,改进了Stream API,并将新方法添加到Stream接口。这些方法如下表所示。

Modifier and Type Method Description
default Stream takeWhile(Predicate 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 dropWhile(Predicate 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 Stream ofNullable(T t) It returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream.
static Stream iterate(T seed, Predicate hasNext, UnaryOperator 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()方法

Stream takeWhile方法采用与其谓词匹配的每个元素。当得到不匹配的元素时,它停止。它返回包含所有匹配元素的元素子集,流的其他部分被丢弃。

Java Stream takeWhile()方法示例1

在此示例中,我们有一个整数列表,并使用takewhile方法获取了偶数值。

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamExample {
public static void main(String[] args) {
List list 
    = Stream.of(1,2,3,4,5,6,7,8,9,10)
            .takeWhile(i -> (i % 2 == 0)).collect(Collectors.toList()); 
System.out.println(list);
}
}

此示例返回一个空列表,因为它在第一个列表元素处失败,并且takewhile在此处停止。

输出:

[]

Java Stream takeWhile()方法示例2

In this example, we are getting first two elements because these are even and stops at third element.