Is there Java stream equivalent to while with variable assignment

大憨熊 提交于 2019-12-04 01:17:18

问题


Is there any stream equivalent to the following

List<Integer> ints;
while (!(ints = this.nextInts()).isEmpty()) {
// do work
}

回答1:


first, thanks for the @Olivier Grégoire comments. it change my answer to a new knowledge.

write your own Spliterator for the unknown size nextInts, then you can using StreamSupport#stream to create a stream for nextInts. for example:

generateUntil(this::nextInts, List::isEmpty).forEach(list -> {
    //do works
});

import static java.util.stream.StreamSupport.stream;

<T> Stream<T> generateUntil(final Supplier<T> generator, Predicate<T> stop) {
    long unknownSize = Long.MAX_VALUE;

    return stream(new AbstractSpliterator<T>(unknownSize, Spliterator.ORDERED) {
        @Override
        public boolean tryAdvance(Consumer<? super T> action) {
            T value = generator.get();

            if (stop.test(value)) {
                return false;
            }

            action.accept(value);
            return true;
        }
    }, false);
}


来源:https://stackoverflow.com/questions/44700006/is-there-java-stream-equivalent-to-while-with-variable-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!