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!
String[][] multiArray = {{"1","2","3"},{"4","5","6"}};
String[] strings = Arrays.stream(multiArray)
.flatMap(Arrays::stream)
.toArray(size -> new String[size]);
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];
}
}
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