Mohamed Gad-Elrab Mohamed Gad-Elrab - 2 years ago 110
Java Question

Concatenate list of Objects arrays in Java8

I have list of 1D arrays wrapped in an object, I want to collect them in 1 single array using java-8 stream and collect.

Given class Item with an array of

class A{
int x;

class Item{
A[] parts=new A[];
public A[] getParts(){
return parts;

So if I have list l

List<Item> l=new ArrayList<>();
l.add(new Item());
l.add(new Item());

I need to collect the content in these two object in one single array of type A.

So if first Item has
and 2nd Item
the output should be somehow like

A[] out={1,2,3,4}

I tried to do A[n]);

but apperantly it has meany problems.

Answer Source

Map each Item to its A[] array. Then when having a stream of A[] just flat map it to get each A of each array and make it one array at the end.

A[] array = -> x.getParts())
                      .flatMap(x ->
                      .toArray(A[]::new); // [1, 2, 3, 4]

However, if you only interested in the int value, there is an extra step

int[] array = -> x.getParts())
                      .flatMap(x ->
                      .mapToInt(x -> x.getX())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download