Convert 2D List to 2D ArrayList in Java

kodazys :

I am trying to convert a 2D List to a 2D ArrayList in Java I will then convert the 2D ArrayList to a 2D Array and implement for loops to return the absolute difference of the 2 diagonals of the matrix.

How would I convert the 2D ArrayList arr to a 2D ArrayList?

Here is my work so far in attempting to convert the input List to an ArrayList:

    public static int diagonalDifference(List<List<Integer>> arr) {

    //first: 2D List --> 2D ArrayList
    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);

    //second: 2D ArrayList --> int[][]

    //third: nested for loop through int[][]to difference between diagonals of 2d array
    }

Here is my full code so far.

 public static int diagonalDifference(List<List<Integer>> arr) {
    List<List<Intger>> arrList = new ArrayList<>();

    int[][] a = new int[arr.size()][];
    for (int i=0; i<arr.size(); i++) {
        List<Integer> row = arr.get(i);
        a[i] = row.toArray(new int[row.size()]);
    }

        int pri = 0;
        int sec =0;

    for(int i=0; i<a.length; i++) {
        for(int j=0; j <a.length; j++) {

            if (a[i] == a[j]) {
                pri += a[i];
            }

            if (i == a.length - j - 1) {
                sec += a[i];
            }

        }
    }
    return Math.abs(pri - sec);

}
YCF_L :

I think you are looking for :

public static int[][] diagonalDifference(List<List<Integer>> arr) {
    return arr.stream()
            .map(a -> a.stream().mapToInt(Integer::valueOf).toArray())
            .toArray(int[][]::new);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=420770&siteId=1