Limit a stream by a predicate

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

        IntStream.iterate(1, n -> n + 1)
        .peek(System.out::println) //it will be executed 9 times
        .filter(n->n>=9)
        .findAny();
    

    instead of peak you can use mapToObj to return final object or message

        IntStream.iterate(1, n -> n + 1)
        .mapToObj(n->{   //it will be executed 9 times
                if(n<9)
                    return "";
                return "Loop repeats " + n + " times";});
        .filter(message->!message.isEmpty())
        .findAny()
        .ifPresent(System.out::println);
    

提交回复
热议问题