Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading