Does Stream#findFirst() (or findAny) shortcircuit a flatmapped stream?

942 Views Asked by At

Java 8 Stream#findFirst() is a short-circuiting terminal operation. Meaning it will stop generating the stream once an element is found (usually used with a filter() operation).

However, I want to know if it will short circuit on a stream created by flatmap. I.e. will it short circuit the streams created within the flatmap operation.

In other words, which code is more efficient (in terms of generating fewer elements in the stream):

Example 1 (with flatmap):

    // produce range 0..99 (10 elements at a time)
    return IntStream.rangeClosed(0, 9)
        .flatMap(i -> IntStream.rangeClosed(i * 10, i * 10 + 9))
        .filter(i -> i == 55)
        .findFirst()
        .getAsInt();

Example 2 (no flatmap):

    // produce range 0..99 (all 100 elements at once)
    return IntStream.rangeClosed(0, 99)
        .filter(i -> i == 55)
        .findFirst()
        .getAsInt();
1

There are 1 best solutions below

1
wilmol On BEST ANSWER

Answer is yes (using Java 11)

using peek:

Example 1 (with flatmap):

    // produce range 0..99 (10 elements at a time)
    return IntStream.rangeClosed(0, 9)
        .flatMap(i -> IntStream.rangeClosed(i * 10, i * 10 + 9))
        .peek(System.out::println)
        .filter(i -> i == 55)
        .findFirst()
        .getAsInt();

Example 2 (no flatmap):

    // produce range 0..99 (all 100 elements at once)
    return IntStream.rangeClosed(0, 99)
        .peek(System.out::println)
        .filter(i -> i == 55)
        .findFirst()
        .getAsInt();

Both generated 56 elements. (Originally thought it would be 60 with flatmap.)