Limit a stream by a predicate

前端 未结 19 3403
别跟我提以往
别跟我提以往 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:43

    takeWhile is one of the functions provided by the protonpack library.

    Stream infiniteInts = Stream.iterate(0, i -> i + 1);
    Stream finiteInts = StreamUtils.takeWhile(infiniteInts, i -> i < 10);
    
    assertThat(finiteInts.collect(Collectors.toList()),
               hasSize(10));
    

提交回复
热议问题