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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With