Often I find the need to concatenate Stream
instances together. If there are just two then the Stream.concat(Stream,Stream)
utility method is perfect, but often I have 3 or more to combine and I'd like to identify the best construct to achieve that.
Clearly I could compose calls to Stream.concat(Stream,Stream)
, but this seems a little illegible, especially if the composed streams are each more complicated expressions:
Stream.concat(a, Stream.concat(b, Stream.concat(c, d)))
Recently I've been favouring using .flatMap(Function.identity())
as a more succinct variation that I think reads more clearly:
Stream.of(a, b, c, d).flatMap(Function.identity())
Although in writing up the question it also occurs to me that an even more succinct option would be to use Stream.concat(Stream,Stream)
in a reduce(..)
call:
Stream.of(a, b, c, d).reduce(Stream::concat)
I notice the java docs warn against repeated concatenation though, which made me wonder would the flatMap(..)
approach have the same limitation? Are there other pros/cons I should be aware of before making an otherwise aesthetic choice?