简体   繁体   中英

How do you unpack a 2D array?

If i have a 2D array:

int[][] a = {
        {1, 2, 3}, 
        {4, 5, 6, 9}, 
        {7}, 
    };

How would i unpack it into:

int[] a = {1, 2, 3, 4, 5, 6, 9, 7}

I know that you can use a for loop to do this but it seems really clunky and i was wondering if there was a better way to do this:

int[] b = new int[9]
for (int i = 0; i < a.length; ++i) {
    for(int j = 0; j < a[i].length; ++j) {
         b.append([i][j])
    }
}

Using streams it's easy.

  • the first stream returns individual 1D arrays (the rows essentially).
  • the next one flattens each of those into a single stream.
  • then that stream is collected back into an array.
int[][] a = {
        {1, 2, 3}, 
        {4, 5, 6, 9}, 
        {7}, 
    };
int[] oneD = Arrays.stream(a).flatMapToInt(Arrays::stream).toArray();
System.out.println(Arrays.toString(oneD));

Prints

[1, 2, 3, 4, 5, 6, 9, 7]

Less concise, but more fast and straightforward solution of your problem:

void unpack2D(int[][] arr2d) {
        int acumulator = 0;
        for(int[] innerArr: arr2d){
            acumulator += innerArr.length;     
        }
        int[] b = new int[acumulator];
        int pointer = 0;
        for (int[] innerArr: arr2d) {
            System.arraycopy(innerArr, 0, b, pointer, innerArr.length);
            pointer += innerArr.length;
        }
        System.out.println(Arrays.toString(b));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM