Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change rows to columns in ArrayList<Integer[]>

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?

like image 663
Klausos Klausos Avatar asked Jan 09 '12 10:01

Klausos Klausos


People also ask

Can ArrayList store different data types?

ArrayList is a kind of List and List implements Collection interface. The Collection container expects only Objects data types and all the operations done in Collections, like iterations, can be performed only on Objects and not Primitive data types. An ArrayList cannot store ints.

How to get values from ArrayList of ArrayList in Java?

The get() method of the ArrayList class accepts an integer representing the index value and, returns the element of the current ArrayList object at the specified index. Therefore, if you pass 0 to this method you can get the first element of the current ArrayList and, if you pass list.


2 Answers

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));
like image 152
Bohemian Avatar answered Sep 21 '22 07:09

Bohemian


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.

like image 21
bchetty Avatar answered Sep 23 '22 07:09

bchetty