简体   繁体   English

有没有一种方法可以在Java中将2维数组添加到2维数组列表中?

[英]Is there a way of adding 2 dimmensional array to 2 dimmensional array list in java?

I know how to add a one dimmensional array to a one dimmensional array list ie 我知道如何将一个维度数组添加到一个维度数组列表,即

 ArrayList<Integer> arrayList = new ArrayList<Integer>  
 (Arrays.asList(array));

However,I'm not sure what needs to be done to add a two dimmensional array to a two dimmensional array list .Below posted is the code. 但是,我不确定要将两个二维数组添加到两个二维数组列表中需要做什么。下面是代码。

 int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};

 ArrayList<Integer> arrayList = new ArrayList<Integer>
 (Arrays.asList(myPoints));????

If you want to preserve one-dimensional arrays from int[][] it's basically: 如果要保留int [] []的一维数组,则基本上是这样的:

ArrayList<int[]> arrOfArr = new ArrayList<int[]>();
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};

arrOfArr.addAll(Arrays.asList(myPoints)); // here's the one-liner doing the job

And if you want to flatten your 2D array to list of integers there's no other way than do it manually by iterating over every element of your array. 而且,如果您想将2D数组展平为整数列表,除了通过遍历数组的每个元素手动进行操作外,别无其他方法。 Which, I suppose, you can. 我想可以。

If Java 8 is an option for you, you could use the Stream API to accomplish what you want in one line: 如果你的Java 8是一个选择,你可以使用流API来完成你在一行想要的东西:

int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
List<List<Integer>> myPointsAsList = 
    Stream.of(myPoints).map(point -> Arrays.asList(point))
    .collect(Collectors.toList());

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

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