Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transfer a Two-Dimensional array to Two-Dimensional ArrayList?

I have this piece of code:

int[][] pattern = new int[][]{
        { 1, 1, 1, 1, 1, 1, 1 },
        { 1, 2, 0, 0, 0, 2, 1 },
        { 1, 0, 3, 0, 3, 0, 1 },
        { 1, 0, 0, 4, 0, 0, 1 },
        { 1, 0, 3, 0, 3, 0, 1 },
        { 1, 2, 0, 0, 0, 2, 1 },
        { 1, 1, 1, 1, 1, 1, 1 },
};

I need to get this 2d array into a 2d ArrayList so i can manipulate it by adding rows and columns to move the pattern around. For example when my method calls for a shift of 2 rows and 2 columns i will be able to move the pattern to something like this:

        { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
        { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
        { 0, 0, 1, 1, 1, 1, 1, 1, 1 },
        { 0, 0, 1, 2, 0, 0, 0, 2, 1 },
        { 0, 0, 1, 0, 3, 0, 3, 0, 1 },
        { 0, 0, 1, 0, 0, 4, 0, 0, 1 },
        { 0, 0, 1, 0, 3, 0, 3, 0, 1 },
        { 0, 0, 1, 2, 0, 0, 0, 2, 1 },
        { 0, 0, 1, 1, 1, 1, 1, 1, 1 },

I'm just looking to get the 2d array into a 2d Arraylist any help will be greatly appreciated!

like image 381
HexxNine Avatar asked Mar 03 '16 02:03

HexxNine


1 Answers

Case 1 It is short, but need to covert the primitive type to reference type (int to Integer) as needed for Arrays.asList();

Integer[][] pattern = new Integer[][]{
        { 1, 1, 1, 1, 1, 1, 1 },
        { 1, 2, 0, 0, 0, 2, 1 },
        { 1, 0, 3, 0, 3, 0, 1 },
        { 1, 0, 0, 4, 0, 0, 1 },
        { 1, 0, 3, 0, 3, 0, 1 },
        { 1, 2, 0, 0, 0, 2, 1 },
        { 1, 1, 1, 1, 1, 1, 1 },
};
List<List<Integer>> lists = new ArrayList<>();
for (Integer[] ints : pattern) {
    lists.add(Arrays.asList(ints));
}

Case 2 If you don't want to covert the primitive type to reference type: (int[][] pattern = new int[][] to Integer[][] pattern = new Integer[][])

List<List<Integer>> lists = new ArrayList<>();
for (int[] ints : pattern) {
    List<Integer> list = new ArrayList<>();
    for (int i : ints) {
        list.add(i);
    }
    lists.add(list);
}
like image 163
Bahramdun Adil Avatar answered Oct 07 '22 00:10

Bahramdun Adil