0

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!

Allen
  • 13
  • 1
  • 2
    What did you try so far? If you can provide some code, guys/gals here can help you better. By the way, Java Stream API's map, filter and collect methods can help you I guess. You can check the official documentation of Stream API (https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html) or you can check some examples online. – stuck Oct 21 '21 at 04:24
  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 21 '21 at 05:20

1 Answers1

0

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

Arthur Klezovich
  • 2,595
  • 1
  • 13
  • 17