java – Stream. Is findany a short circuit operation?

Consider this code

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

Will it process the entire stream and call mypredicate1 and mypredicate2 for all elements of the collection? Or, how many predicates need to be called to actually find the value?

Solution

Yes, just like stream The findany() file describes:

This is a common misconception that objects in a stream are "pushed" onto consuming operations It's actually another way - consuming operations pull each element

For sequential streams, many predicates are called only when finding a matching value Parallel flow can execute more predicates, but it will also stop executing immediately after finding the element

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());
  }
}

Will print:

getI: 1
getI: 2
getI: 3
Found: 3
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>