Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an element to the end of a stream for each element already in the stream

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.

like image 637
Jens Schauder Avatar asked Sep 18 '17 11:09

Jens Schauder


1 Answers

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.

like image 174
GhostCat Avatar answered Oct 12 '22 23:10

GhostCat