[英]How to convert List of int array to 2D Array?
Given a list of int[] [{7, 0}, {7, 1}, {6, 1}, {5, 0}, {5, 2}, {4, 4}]
I need to convert it into 2D Array {{7, 0}, {7, 1}, {6, 1}, {5, 0}, {5, 2}, {4, 4}}
using Java 8.给定一个
int[] [{7, 0}, {7, 1}, {6, 1}, {5, 0}, {5, 2}, {4, 4}]
的列表,我需要将其转换为二维数组{{7, 0}, {7, 1}, {6, 1}, {5, 0}, {5, 2}, {4, 4}}
使用 Java 8。
Before Java 8 we could use the following logic: temp
is List<int[]>
which contains above list of elements.在 Java 8 之前,我们可以使用以下逻辑:
temp
是包含上述元素列表的List<int[]>
。 First res[][]
is created of the same size as a List of elements in temp
.首先
res[][]
创建的大小与temp
中的元素列表相同。
int[][] res = new int[temp.size()][2];
for (int i = 0; i < temp.size(); i++) {
res[i][0] = temp.get(i)[0];
res[i][1] = temp.get(i)[1];
}
Try this.尝试这个。
List<int[]> list = List.of(
new int[] {7, 0}, new int[] {7, 1},
new int[] {6, 1}, new int[] {5, 0},
new int[] {5, 2}, new int[] {4, 4});
int[][] res = list.stream().toArray(int[][]::new);
System.out.println(Arrays.deepToString(res));
result结果
[[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]]
See this code run live at IdeOne.com .请参阅在 IdeOne.com 上实时运行的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.