Limit a stream by a predicate

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

    I have another quick solution by implementing this (which is rly unclean in fact, but you get the idea):

    public static void main(String[] args) {
        System.out.println(StreamUtil.iterate(1, o -> o + 1).terminateOn(15)
                .map(o -> o.toString()).collect(Collectors.joining(", ")));
    }
    
    static interface TerminatedStream {
        Stream terminateOn(T e);
    }
    
    static class StreamUtil {
        static  TerminatedStream iterate(T seed, UnaryOperator op) {
            return new TerminatedStream() {
                public Stream terminateOn(T e) {
                    Builder builder = Stream. builder().add(seed);
                    T current = seed;
                    while (!current.equals(e)) {
                        current = op.apply(current);
                        builder.add(current);
                    }
                    return builder.build();
                }
            };
        }
    }
    

提交回复
热议问题