I'm confused on this situation:
- I've a
Producer
which produces an undetermined number of items from an underlining iterator, possibly a large number of them. - Each item must be mapped to a different interface (eg, wrapper, JavaBean from JSON structure).
- So, I'm thinking that it would be good for
Producer
to return a stream, it's easier to write code that convertIterator
toStream
(usingSpliterators
andStreamSupport.stream()
), then applyStream.map()
and return the final stream. - The problem is I have an invoker that does nothing with the resulting stream, eg, a unit test, yet I still want the mapping code to be invoked for every item. At the moment I'm simply calling
Stream.count()
from the invoker to force that.
Questions are:
- Am I doing it wrong? Should I use different interfaces? Note that I think implementing
next()/hasNext()
forIterator
is cumbersome, mainly because it forces you to create a new class (even if it can be anonymous) and keep a pointer and check it. Same for collection views, returning a collection that is created and not a dynamic view over the underlining iterator is out of question (the input data set might be very large). The only alternative I like so far is a Java implementation ofyield()
. Neither do I want the stream to be consumed inside Producer (ie,forEach()
), since some other invoker might want it to perform some real operation. - Is there a better best practice to force the stream processing?