eggyal eggyal - 11 months ago 46
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


Foo[] concatenation = streamOfFooArrays.collect(Collector.of(
(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 Source

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)