Performing an intermediate sorted group-by operation on a Java stream

90 views Asked by At

I have a Java Stream of tuple objects like so:

{ 1, 2 }
{ 1, 6 }
{ 2, 3 }
{ 3, 10 }
{ 3, 12 }
{ 3, 20 }

These tuples are guaranteed to be ordered by their first element. I want to convert this stream into another stream of tuples like so:

{ 1, [2, 6] }
{ 2, [3] }
{ 3, [10, 12, 20] }

But, here's the key, I want this to be an intermediate operation - I don't need to evaluate the entirety of the first stream to output each group, because the tuples are already ordered as required. What I want is something like an intermediate collector, but I can't find a way of doing that in the stream API.

Can anyone think of a way of doing this without iterating the entire stream?

0

There are 0 answers