Hi Olexandr,

Great question!

I guess a "simple" implementation of an N-ary concat could work, but it would 
have performance implications (think a recursive use of Stream.concat()) but if 
you look at the implementation of Stream.concat's backing Spliterator, you'll 
see how complex it would be to implement it in a truly N-ary way (a challenging 
exercise for the reader?): 
https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/stream/Streams.java#L690


Cheers,
√


Viktor Klang
Software Architect, Java Platform Group
Oracle
________________________________
From: core-libs-dev <[email protected]> on behalf of Olexandr 
Rotan <[email protected]>
Sent: Wednesday, 17 September 2025 15:58
To: core-libs-dev <[email protected]>
Subject: Stream.concat with varagrs

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