eggyal eggyal - 2 months ago 7
Java Question

How should one concatenate a stream of arrays?

I would like to concatenate a stream of arrays via a mutable accumulator.

Currently I am doing the following for

Stream<Foo[]>
:

Foo[] concatenation = streamOfFooArrays.collect(Collector.of(
ArrayList<Foo>::new,
(acc , els ) -> {acc.addAll(Arrays.asList(els));},
(acc1, acc2) -> {acc1.addAll(acc2); return acc1;},
acc -> acc.toArray(new Foo[x.size()])
));


However, for something that feels quite generically useful, it's disappointing that the standard library doesn't provide something more immediate.

Have I overlooked something, or is there A Better Way?

Answer

You can use flatMap to flatten the elements of the arrays into a Stream<Foo> and then generate the output array using toArray :

Foo[] concatenation = streamOfFooArrays.flatMap(Arrays::stream)
                                       .toArray(Foo[]::new);
Comments