Limit a stream by a predicate

前端 未结 19 3035
别跟我提以往
别跟我提以往 2020-11-21 22:54

Is there a Java 8 stream operation that limits a (potentially infinite) Stream until the first element fails to match a predicate?

In Java 9 we can use

19条回答
  •  伪装坚强ぢ
    2020-11-21 23:49

    allMatch() is a short-circuiting function, so you can use it to stop processing. The main disadvantage is that you have to do your test twice: once to see if you should process it, and again to see whether to keep going.

    IntStream
        .iterate(1, n -> n + 1)
        .peek(n->{if (n<10) System.out.println(n);})
        .allMatch(n->n < 10);
    

提交回复
热议问题