Well there will be a way to iterate with streams like a for loop or an iterator - via Stream.iterate
, but it will be present in jdk-9. But it is not that trivial to use - because it acts exactly like a for loop and thus not exactly what you might expect. For example:
Iterator<Integer> iter = List.of(1, 2, 3, 4).iterator();
Stream<Integer> stream = Stream.iterate(iter.next(),
i -> iter.hasNext(),
i -> iter.next());
stream.forEach(System.out::println); // prints [1,2,3]
Or this:
Iterator<Integer> iter = List.of(1).iterator();
Stream.iterate(iter.next(), i -> iter.hasNext(), i -> iter.next())
.forEach(System.out::println); // prints nothing
For the case that you need there's the forEachRemaining
, but it's no "magic", internally it does exactly what you do:
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}