← 中文资源

简体中文版本

Stream 三个 match 的短路语义

anyMatch、allMatch、noneMatch 都在拿到决定性元素时短路停止消费流;空流上 allMatch 与 noneMatch 返回 true、anyMatch 返回 false。

阅读英文原文

实现说明

Stream 三个 match 的短路语义以类 MatchShortCircuit和函数 main为骨架。 数据流经 stream 管道,每个阶段都返回新视图而不做原地修改。

使用要点

  • 跑完文件,输出里会留下标记——any overdrawn:、all positive:、none over 500:。

常见问题

运行「Stream 三个 match 的短路语义」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 any overdrawn:、all positive:、none over 500: 标签标明各步骤。

核心语句

List<Integer> balances = List.of(120, -5, 300, 40);

代码示例

import java.util.List;

public class MatchShortCircuit {

    public static void main(String[] args) {
        List<Integer> balances = List.of(120, -5, 300, 40);

        // anyMatch:找到第一个满足的元素就短路,不再消费剩余元素
        System.out.println("any overdrawn: " + balances.stream().anyMatch(b -> b < 0));

        // allMatch:遇到第一个不满足的就短路返回 false
        System.out.println("all positive: " + balances.stream().allMatch(b -> b > 0));

        // noneMatch:找到违例即短路返回 false
        System.out.println("none over 500: " + balances.stream().noneMatch(b -> b > 500));

        // 空流的结论:allMatch 与 noneMatch 是 true(没有反例),anyMatch 是 false
        System.out.println("empty all: " + List.<Integer>of().stream().allMatch(b -> b > 0));
        System.out.println("empty any: " + List.<Integer>of().stream().anyMatch(b -> b > 0));
    }
}