我正在写一个方法来转换 Integer
来自 List
的数据类型的 List
s,到数组的原始数组,键入 int[][]
.
问题
有什么办法可以转换Integer
至 int
使用 Java API?
供您引用,int[] set
将用于其他用途,请忽略。
我发现了什么
Apache Commons API“toPrimitive”方法将 Integer 转换为 int 类型。但是,我只是在寻找使用 native Java API 的解决方案。
到目前为止,这是我的代码
class Test {
int[][] convert(int[] set) {
List<List<Integer>> ll = new ArrayList<List<Integer>>();
ll.add(new ArrayList<Integer>());
ll.add(new ArrayList<Integer>());
ll.add(new ArrayList<Integer>());
ll.get(0).add(1);
ll.get(0).add(2);
ll.get(1).add(2);
ll.get(2).add(3);
System.out.println(ll + " " + ll.size());
int[][] tempArray = new int[0][0];
for (int i = 0; i < ll.size(); i++) {
for (int j = 0; j < ll.get(i).size(); j++) {
tempArray[i][j] = ll.get(j);
}
}
return tempArray;
}
}
预期结果
List entry: [[1,2],[2],[3]]
return: {{1,2},{2},{3}}
错误
tempArray[i][j] = ll.get(j);
返回 java.util.List<java.lang.Integer> cannot be converted to int
.
最佳答案
要回答您的确切问题,是的,可以使用 intValue()
方法将 Integer
转换为 int
,或者您可以使用自动装箱以转换为 int
。
所以你的循环的最里面的部分可能是这些中的任何一个:
tempArray[i][j] = ll.get(i).get(j).intValue();
tempArray[i][j] = ll.get(i).get(j);
但是,我们也可以采取不同的策略。
作为 this answer 的修改对于类似的问题,在 Java 8 中,您可以使用 Streams 映射到整数数组。这种结构只需要一个额外的映射层。
List<List<Integer>> list = new ArrayList<>();
int[][] arr = list.stream()
.map(l -> l.stream().mapToInt(Integer::intValue).toArray())
.toArray(int[][]::new);
Ideone Demo
关于java - 将 List<List<Integer>> 转换为 int[][],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39030219/