CloseableStreamIterator implements AutoCloseable, Iterator<T> { public Stream<T> getRemainingStream() { try (CloseableStreamIterator<T> self = this) { Stream<T> result = toStream(this.iterator) .onClose(this.stream::close); this.stream = null; this.iterator = null; return result; } } CloseableStreamIterator(Supplier<Stream<T>> streamSupplier); @Override boolean hasNext(); @Override T next(); @Override void close(); Stream<T> getRemainingStream();  }
@Test @DisplayName("can pick up streaming after partial iteration") public void testGetRemainingStream() { CloseableStreamIterator<String> iter = newInstance(); int splitPosition = 2; for (int i = 0; i < splitPosition; i++) { assertThat(iter.hasNext()).isTrue(); assertThat(iter.next()).isEqualTo(DATA[i]); } assertThat(iter.hasNext()).isTrue(); Stream<String> remaining = iter.getRemainingStream(); AtomicInteger index = new AtomicInteger(splitPosition); remaining.forEach(datum -> { assertThat(datum).isEqualTo(DATA[index.getAndIncrement()]); }); }