How to change rows to columns in ArrayList<Integer[]>
17,467
Solution 1
Anything wrong with int[][]
? That would be the standard approach:
public static void main(String[] args) {
int[][] table = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } };
// This code assumes all rows have same number of columns
int[][] pivot = new int[table[0].length][];
for (int row = 0; row < table[0].length; row++)
pivot[row] = new int[table.length];
for (int row = 0; row < table.length; row++)
for (int col = 0; col < table[row].length; col++)
pivot[col][row] = table[row][col];
for (int row = 0; row < pivot.length; row++)
System.out.println(Arrays.toString(pivot[row]));
}
Output:
[1, 4]
[2, 5]
[3, 6]
If you must use Collections, use as a start:
List<List<Integer>> table = new ArrayList<List<Integer>>();
table.add(Arrays.asList(1, 4));
table.add(Arrays.asList(2, 5));
table.add(Arrays.asList(3, 6));
Solution 2
This problem is called 'Matrix Transpose'. If you know the number of rows beforehand, you could just use the 2D matrix and just transpose it, as below:
Integer[][] matrix = new Integer[rows][cols];
//Let i = 2 (rows); j = 3 (cols)
matrix[0] = new Integer[]{1,2,3};
matrix[1] = new Integer[]{4,5,6};
Integer[][] transposedMatrix = new Integer[cols][rows];
for(int i=0;i<cols;i++) {
for(int j=0;j<rows;j++) {
transposedMatrix[i][j] = matrix[j][i];
}
}
Even if you don't know the number of rows or columns beforehand, you can use other datastructures like ArrayList and then use the same logic as above.
Solution 3
You can use two loops - something like this should work:
ArrayList<Integer[]> res = ArrayList<Integer[]>();
int C = arr.get(0).length;
int R = arr.size();
for (int c = 0 ; c != C ; c++) {
int[] row = new Integer[R];
for (int r = 0 ; r != R ; r++) {
row[r] = arr.get(R)[c];
}
res.add(row);
}
Solution 4
ArrayList<Integer[]> arr = new ArrayList<Integer[]>();
arr.add(new Integer[]{1,2,3});
arr.add(new Integer[]{4,5,6});
ArrayList<Integer[]> res = new ArrayList<Integer[]>();
int C = arr.get(0).length;
int R = arr.size();
for (int c = 0 ; c != C ; c++) {
Integer[] row = new Integer[R];
for (int r = 0 ; r < R ; r++) {
row[r] = arr.get(r)[c];
}
res.add(row);
}
Author by
Klausos Klausos
Updated on June 26, 2022Comments
-
Klausos Klausos almost 2 years
How to change rows to columns in
ArrayList<Integer[]>
? For instance:ArrayList<Integer[]> arr = ArrayList<Integer[]>(); arr.add(new Integer[]{1,2,3}); arr.add(new Integer[]{4,5,6});
It should be:
[1]: 1 4 [2]: 2 5 [3]: 3 6
If it´s impossible with ArrayList, what are the other options to store 2D data and change rows to columns?
-
4ndrew over 12 years@Bohemian to preserve order you can use LinkedHashMap impl.