anon
anon

Reputation:

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?

Upvotes: 5

Views: 234

Answers (1)

Eran
Eran

Reputation: 393936

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);

Upvotes: 7

Related Questions