Inclusive takeWhile() for Streams

后端 未结 2 442
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 10:25

I want to know if there is a way to add the last element of the stream that was tested against the condition of the method takeWhile(). I believe I want to achieve something

2条回答
  •  渐次进展
    2021-01-15 10:57

    There's no convenient way to do that with the normal stream API. It is possible in an ugly way (you would need to adapt this implementation, that's just a normal takeWhile "backported" for Java 8).

    This guy has written a stream extension library which has takeWhileInclusive.

    Sample usage:

    IntStreamEx.of(1, 3, 2, 5, 4, 6)
        .peek(foo -> System.out.println("Peek: " + foo))
        .takeWhileInclusive(n -> n < 5)
        .forEach(bar -> System.out.println("forEach: " + bar));
    

提交回复
热议问题