How to combine a stream of arrays?

I would like to combine a stream of arrays through a mutable drive.

I am currently 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 seems quite useful in general, it disappoints that the standard library does not provide something more immediate.

Am I missing something, or is there a better way?

+5
source share
1 answer

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

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

All Articles