简体   繁体   English

如何使用二维数组初始化二维 arraylist?

[英]How to initialize 2D arraylist using 2D array?

I have this array我有这个数组

int[][] currGrid = {{1,1},{1,2},{2,2}}; int[][] currGrid = {{1,1},{1,2},{2,2}};

And this array is static so I want to create 2D arraylist using the same elements.这个数组是 static 所以我想使用相同的元素创建 2D arraylist。 Is there any way to create the arraylist for same in a single line without using add in Java?有没有什么方法可以在一行中创建相同的 arraylist 而无需在 Java 中使用 add?

It's unclear to me whether you meant you want to convert this given 2D array to a 2D list, or wether you meant to just create a new list with these values as a one-liner.我不清楚您是要将此给定的 2D 数组转换为 2D 列表,还是要创建一个具有这些值的新列表作为单行。

If you meant the former, you could stream the array and then stream each of its elements, and collect them:如果你的意思是前者,你可以 stream 数组,然后 stream 它的每个元素,并收集它们:

List<List<Integer>> currGridList = 
    Arrays.stream(currGrid)
          .map(g -> Arrays.stream(g).boxed().collect(Collectors.toList()))
          .collect(Collectors.toList());

If you meant the latter, you could use List.of :如果你的意思是后者,你可以使用List.of

List<List<Integer>> currGridList = List.of(List.of(1, 1), List.of(1, 2), List.of(2, 2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM