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

Viewed 186

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.

3 Answers
Related