Search code examples
javajava-stream

The allMatch operation on infinite stream terminates in Java


I'm preparing for the OCP exam. In a book there's the following review question the answer to which turned out to be the allMatch terminal operation:

var s = Stream.generate(() -> "meow");
var match = s.allMatch(String::isEmpty);
System.out.println(match);

It executes and prints false

My question is how does Java can determine that exactly all the elements match the predicate while the stream is infinite and supposed to hang?

My answer was the anyMatch option and it actually hangs...


Solution

  • allMatch didn't "determine that exactly all the elements match the predicate". If it had, it would have returned true.

    It determined that "there is one element that doesn't match the predicate", which is much easier to do. After that, allMatch can just return false.

    For anyMatch, it hangs because it was not able to determine that there is any empty strings, and it will never do because this is an infinite stream of non-empty strings.

    If there were one empty string in the stream, anyMatch would return true once it finds that string.