【问题标题】:How to convert List of int array to 2D Array?如何将 int 数组列表转换为 2D 数组?
【发布时间】:2020-10-26 02:51:37
【问题描述】:

给定int[] [{7, 0}, {7, 1}, {6, 1}, {5, 0}, {5, 2}, {4, 4}] 的列表,我需要使用 Java 8 将其转换为二维数组 {{7, 0}, {7, 1}, {6, 1}, {5, 0}, {5, 2}, {4, 4}}

在 Java 8 之前,我们可以使用以下逻辑:tempList<int[]>,其中包含上述元素列表。首先创建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];
}

【问题讨论】:

  • 这适用于 java 8+。我认为您的问题与您使用的 java 版本无关,或者根本不了解问题所在。

标签: java arrays arraylist data-structures java-8


【解决方案1】:

试试这个。

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));

结果

[[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]]

看到这个code run live at IdeOne.com

【讨论】:

  • 赞成,但 list.toArray(int[][]::new)(没有 stream() 调用)也很安静,但它是 Java 11+。对于所有 Java 版本,不仅是 Java 8+,list.toArray(new int[0][]) 工作得很好。
  • List.of 也是java 9+,我不知道在这种情况下使用流是否更好,是否解决了OP问题,如果有的话。
  • 请注意,这是一个浅拷贝。问题中的示例代码进行了深层复制。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 2017-04-04
相关资源
最近更新 更多