Given a function Function<T, T> f
and a Stream<T> ts
what is a good (nice readability, good performance) way of creating a new Stream<T>
which first contains the original elements and then the elements converted by f
.
One might think this would work:
Stream.concat(ts, ts.map(f));
But this doesn't work and results in an exception instead:
java.lang.IllegalStateException: stream has already been operated upon or closed
Note: that the order does matter: original elements have to come first in correct order, then the transformed elements in matching order.
You can't open a bottle of wine and then pass the bottle to another person and ask him to open it again.
Thus I think this is not possible by the nature of streams to do what you ask for.
You have one chain of "processing" per stream. You can't have two.
So the closest you could get at would be working from "its origin", like
Stream.concat(someList.stream(), someList.stream().map(f));
for example. And of course, when you don't have that list, you could go for:
List<Whatever> someList = ts.collect(Collectors.asList());
first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With