I was looking at this link for lazy stream construction and tried using it for one of my cases.
My primary stream has some operations that are needed to be done on Stream.onClose().
In my custom logic, I use Iterator from Stream.iterator() for stream processing.
This worked fine consuming the actual Stream. But, when I used Stream.flatMap() for constructing a lazy stream, onClose function gets called when I start iterating, which in-turn creates problems for me.
I tried this in zulu-opendjk 1.8.0_222 and 13. I am facing this exception in both the environments.
You can reproduce the problem with the below code.
import java.util.*; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class TestStreamIterator { public static void main(String args[]) { Stream<String> stream1 = getStream(); stream1.iterator().forEachRemaining(System.out::println); Stream<String> stream2 = Stream.of(1).flatMap(integer -> getStream()); stream2.iterator().forEachRemaining(System.out::println); } private static Stream<String> getStream() { List<String> values = Arrays.asList("a", "b", "c"); MyIterator iterator = new MyIterator(values); Stream<String> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.NONNULL | Spliterator.IMMUTABLE), false).onClose(iterator::close); return stream; } private static class MyIterator implements Iterator<String>, AutoCloseable { private Iterator<String> iterator; public MyIterator(List<String> values) { iterator = values.iterator(); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public String next() { return iterator.next(); } @Override public void close() { throw new IllegalStateException("Should not come here"); } } } My understating is, when using flatMap; close method of Stream.of(1) only should be called. Not of the stream created inside flatMap function.
I was expecting the onClose function to be invoked only when the stream is closed. But, I am not sure where the stream is getting closed.
Any help on solving this case would also be helpful.
