我想把List<List<Integer>>转换成java中的二维数组。我可以用下面的代码做到这一点,但问题是我的二维数组使用了原始数据类型。
Integer[][] array = new Integer[resultList.size()][];
for (i = 0; i < resultList.size(); i++) {
ArrayList<Integer> row = (ArrayList<Integer>) resultList.get(i);
array[i] = row.toArray(new Integer[row.size()]);
}发布于 2020-05-08 23:04:47
听起来你想要的是int[][]而不是Integer[][]。在这种情况下,我会选择:
int[][] result = resultList.stream()
.map(l -> l.stream().mapToInt(e -> e).toArray())
.toArray(int[][]::new);发布于 2020-05-08 23:15:22
您可以通过迭代List<List<Integer>>并将List<Integer>的元素复制到int [][] array的相应行中来完成此操作。
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<List<Integer>> list = List.of(List.of(10, 20), List.of(5, 15));
int[][] array = new int[list.size()][];
for (int i = 0; i < list.size(); i++) {
array[i] = new int[list.get(i).size()];
for (int j = 0; j < list.get(i).size(); j++) {
array[i][j] = list.get(i).get(j);
}
}
// Display array[][]
System.out.println(Arrays.deepToString(array));
}
}输出:
[[10, 20], [5, 15]]https://stackoverflow.com/questions/61681979
复制相似问题