Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there Java stream equivalent to while with variable assignment

Is there any stream equivalent to the following

List<Integer> ints;
while (!(ints = this.nextInts()).isEmpty()) {
// do work
}
like image 411
Jan Tajovsky Avatar asked Jun 22 '17 12:06

Jan Tajovsky


People also ask

How do you use variables in stream?

You can't use an int as variable because it must be final to be used in a stream. But You can create a class wrapping the int. Then declare the variable holding this class as final. Changing the content of the inner int variable.

What is Stream Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.


Video Answer


1 Answers

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);
}
like image 192
holi-java Avatar answered Nov 08 '22 22:11

holi-java