javajava-streamshort-circuiting

Terminate stream when value matches criteria, otherwise collect into a collection


I am using Java parallel streams for a chess engine. The stream is used to evaluate each chess Move in a given List of Moves. Each Move is mapped to an Integer representing the Move's value, then I collect all the Integers into a List and return the largest Integer in the List.

This seems easy enough, but I want to design my stream to also immediately terminate if an Integer that passes through the stream matches certain criteria.

For example, if I have a list of 100 Moves to be converted into a stream, I want my stream to immediately terminate if any of those Moves is mapped to an Integer that is less than 4, otherwise I want to collect those Integers into a List (this is just an example to help clarify).

I am not sure how to go about doing this (I have thought about short-circuiting operations, but I do not know how to use short-circuiting operations in conjunction with collectors in the event that the stream isn't short-circuited). I am happy to clarify anything also. Thanks!


Solution

  • What you are looking for is the takeWhile operator ...

    Stream.of("cat", "dog", "elephant", "fox", "rabbit", "duck")
      .takeWhile(n -> n.length() % 2 != 0)
      .forEach(System.out::println);
    

    More info in this article