Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
eggyal Avatar asked Sep 06 '16 09:09

eggyal


People also ask

How do you concatenate arrays?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.

How do you concatenate a stream?

concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. The calls to Stream.

How do you concatenate arrays in Java?

5.1. First, we convert two input arrays to Stream objects. Second, we concatenate the two Stream objects using the Stream. concat() method. Finally, we return an array containing all elements in the concatenated Stream.


1 Answers

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);
like image 181
Eran Avatar answered Sep 25 '22 14:09

Eran