Limit a stream by a predicate

前端 未结 19 3039
别跟我提以往
别跟我提以往 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-22 00:01

    Here is my attempt using just Java Stream library.

            IntStream.iterate(0, i -> i + 1)
            .filter(n -> {
                    if (n < 10) {
                        System.out.println(n);
                        return false;
                    } else {
                        return true;
                    }
                })
            .findAny();
    
    0 讨论(0)
提交回复
热议问题