java stream短路_java – Stream.findAny是短路操作吗?

是的,正如

Stream.findAny()文件所述:

This is a short-circuiting terminal operation.

这是一种常见的误解,即流中的对象被“推”到消耗操作上.它实际上是另一种方式 – 消耗操作拉动每个元素.

对于顺序流,只有在查找匹配值时才会调用许多谓词.

并行流可以执行更多谓词,但也会在找到元素后立即停止执行.

public class StreamFilterLazyTest {

static int stI = 0;

static class T {

public T() {

super();

this.i = ++stI;

}

int i;

int getI() {

System.err.println("getI: "+i);

return i;

}

}

public static void main(String[] args) {

T[] arr = {new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T(), new T()};

Optional found = Arrays.stream(arr).filter(t -> t.getI() == 3).findAny();

System.out.println("Found: "+found.get().getI());

}

}

将打印:

getI: 1

getI: 2

getI: 3

Found: 3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值