加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:49:08 所属栏目:Java 来源:网络整理
导读:考虑这段代码 Object found = collection.stream() .filter( s - myPredicate1(s)) .filter( s - myPredicate2(s)) .findAny() 它会处理整个流,并为集合的所有元素调用myPredicate1和myPredicate2吗?或者,实际找到该值需要调用多少个谓词? 解决方法 是的,
考虑这段代码

Object found = collection.stream()
    .filter( s -> myPredicate1(s))
    .filter( s -> myPredicate2(s))
    .findAny()

它会处理整个流,并为集合的所有元素调用myPredicate1和myPredicate2吗?或者,实际找到该值需要调用多少个谓词?

解决方法

是的,正如 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()};
    Optional<T> 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读