Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge a 2D array into a 1D array?

I'm having a hard time to figure out on how to merge multidimensional array into one single array.

Here is my code:

        String[][] multiArray = {{"1","2","3"},{"4","5","6"}};
    String[] singleArray = new String[6];

    for(int i=0; i<singleArray.length; i++)
    {
        for(int x=0; x<multiArray.length; x++)
        {
            for(int z=0; z<multiArray[x].length;z++)
            {
                //for(int i=0; i<singleArray.length; i++)
                //{
                singleArray[i] = multiArray[x][z];  
                //}
            }
        }
    }


    for(String temp : singleArray){
        System.out.println(temp);
    }

The RESULT is

6  
6  
6  
6  
6  
6  

Why is that? How can I put all the numbers into one single array? Many thanks!

like image 758
Austine Avatar asked Dec 15 '22 02:12

Austine


2 Answers

String[][] multiArray = {{"1","2","3"},{"4","5","6"}};
String[] strings = Arrays.stream(multiArray)
        .flatMap(Arrays::stream)
        .toArray(size -> new String[size]);
like image 123
cringineer Avatar answered Dec 16 '22 16:12

cringineer


You need to increment the index of the 1-dimensional array for each entry in the multi-dimensional:

String[][] multiArray = {{"1","2","3"},{"4","5","6"}};
String[] singleArray = new String[6];

for (int x = 0, i = 0; x < multiArray.length; x++) {
    for (int z = 0; z < multiArray[x].length; z++) {
        singleArray[i++] = multiArray[x][z];  
    }
}

Notice that i is initialized in the outer loop, and it's incremented when assigning a value in the 1-dimensional array.

Another equivalent alternative would be incrementing i in the inner loop:

for (int x = 0, i = 0; x < multiArray.length; x++) {
    for (int z = 0; z < multiArray[x].length; z++, i++) {
        singleArray[i] = multiArray[x][z];  
    }
}
like image 42
janos Avatar answered Dec 16 '22 16:12

janos