Limit a stream by a predicate

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

    If you know the exact amount of repititions that will be performed, you can do

    IntStream
              .iterate(1, n -> n + 1)
              .limit(10)
              .forEach(System.out::println);
    

提交回复
热议问题