java - 在 Java 中对流应用过滤器

标签 java filter java-8 java-stream predicate

鉴于以下代码,我希望输出为“-3-2-101231”,因为过滤器应该遍历流的所有项目,从而打印正在评估的项目。当对 allMatch 函数求值时,它应该打印“1”,因为它正在接收正整数流,因此在发现第一个元素非负数后应该短路。

为什么它打印“-3-2-1011”而不是“-3-2-101231”?

    List<Integer> list = Arrays.asList(-3,-2,-1,0,1,2,3);
    Predicate<Integer> positive = i->{
        System.out.print(i);
        return i>0;
    };
    Predicate<Integer> negative = i->{
        System.out.print(i);
        return i<0;
    };

    list.stream().filter(positive).allMatch(negative);

最佳答案

不,过滤器不应该遍历流中的每个项目。那将是一种浪费。一旦 allMatch() 操作看到非负项,管道就会终止。

不保证流中的所有项目都会被过滤;保证由 allMatch() 测试的任何项目都首先通过了前面的过滤器。

您看到的输出是来自过滤器的 -3 -2 -1 0 1,然后是来自最终谓词的 1,这将终止进程。当终端操作已经确定其结果时,无需从上游过滤操作中获取 2。

用文档的话来说,Stream

— Laziness-seeking. Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.

并且,

Processing streams lazily allows for significant efficiencies; in a pipeline such as the filter-map-sum example above, filtering, mapping, and summing can be fused into a single pass on the data, with minimal intermediate state. Laziness also allows avoiding examining all the data when it is not necessary; for operations such as "find the first string longer than 1000 characters", it is only necessary to examine just enough strings to find one that has the desired characteristics without examining all of the strings available from the source. (This behavior becomes even more important when the input stream is infinite and not merely large.)

关于java - 在 Java 中对流应用过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43107654/

相关文章:

css - IE 中的多个 CSS 过滤器

javascript - ngRepeat 按深度属性过滤

java - 预期在单线程上有序执行

java - 比较 java.time.ZonedDateTime 的实例忽略 Java 8 比较中的秒和毫秒瞬间

java - Android:ScrollView 禁用所有按钮和导航

java - 即使使用反射,我什至不希望我的私有(private)方法显示在我的类(class)之外?

Ruby 在一种方法中选择和拒绝

java - 如何将变量转换为度数?

java - 通过字节码将私有(private)类从 Kotlin 转换为 Java

java - 具有不同对象类型的重复代码