Reputation: 149
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);
}
Upvotes: 1
Views: 240
Reputation: 1743
This should also work: I tested just now.
row.stream().mapToInt(Integer::intValue).toArray();
Upvotes: 1
Reputation: 60046
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);
}
Upvotes: 1