Hi,

Not immediately obvious but you can create a Stream<Stream<T>> using
Stream.of and reduce that using Stream::concat to obtain a Stream<T>.

Something along those lines:

```
var stream = Stream.of(Stream.of(1,2,3), Stream.of(4), Stream.of(5, 6, 7, 8)).reduce(Stream.empty(), Stream::concat, Stream::concat);

stream.forEach(System.out::println);

1
2
3
4
5
6
7
8


```

No idea what the perf would be :-)

cheers,

-- daniel
On 17/09/2025 15:15, Pavel Rappo wrote:
  this would be a great quality of life improvement

Is it such a useful use case, though? I mean, it's no different from
SequenceInputStream(...) or Math.min/max for that matter. I very
rarely have to do Math.min(a, Math(min(b, c)) or some such. And those
methods predate streams API by more than a decade.

Separately, it's not just one method. Consider that `concat` is also
implemented in specialized streams such as IntStream, DoubleStream,
and LongStream.

On Wed, Sep 17, 2025 at 2:58 PM Olexandr Rotan
<[email protected]> wrote:

Greetings to everyone on the list.

When working on some routine tasks recently, I have encountered a, seemingly to 
me, strange decision in design of Stream.concat method, specifically the fact 
that it accepts exactly two streams. My concrete example was something along 
the lines of

var studentIds = ...;
var teacherIds = ...;
var partnerIds = ...;

return Stream.concat(
     studentIds.stream(),
     teacherIds.stream(),
     partnerIds.stream() // oops, this one doesn't work
)

so I had to transform concat to a rather ugly
Stream.concat(
     studentIds.stream(),
     Stream.concat(
         teacherIds.stream(),
         partnerIds.stream()
     )
)

Later on I had to add 4th stream of a single element (Stream.of), and this one 
became even more ugly

When I first wrote third argument to concat and saw that IDE highlights it as 
error, I was very surprised. This design seems inconsistent not only with the 
whole java stdlib, but even with Stream.of static method of the same class. Is 
there any particular reason why concat takes exactly to arguments?

I would say that, even if just in a form of sugar method that just does reduce 
on array (varagrs) of streams, this would be a great quality of life 
improvement, but I'm sure there also may be some room for performance 
improvement.

Of course, there are workarounds like Stream.of + flatmap, but:

1. It gets messy when trying to concat streams of literal elements set 
(Stream.of) and streams of collections or arrays
2. It certainly has significant performance overhead
3. It still doesn't explain absence of varagrs overload of concat

So, once again, is there any particular reason to restrict arguments list to 
exactly two streams? If not, I would be happy to contribute 
Stream.concat(Stream... streams) overload.

Best regards




Reply via email to