Limit a stream by a predicate

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

    Actually there are 2 ways to do it in Java 8 without any extra libraries or using Java 9.

    If you want to print numbers from 2 to 20 on the console you can do this:

    IntStream.iterate(2, (i) -> i + 2).peek(System.out::println).allMatch(i -> i < 20);
    

    or

    IntStream.iterate(2, (i) -> i + 2).peek(System.out::println).anyMatch(i -> i >= 20);
    

    The output is in both cases:

    2
    4
    6
    8
    10
    12
    14
    16
    18
    20
    

    No one mentioned anyMatch yet. This is the reason for this post.

提交回复
热议问题