在java中将二维数组转换为List?

我有一个对象的m X n二维数组说Foo 。 所以我有Foo[][] foosArray 。 在Java中将其转换为List的最佳方法是什么?

这是为任何二维数组执行此操作的一种很好的方法,假设您按以下顺序进行操作:

[[array [0] -elems],[array [1] elems] …]

 public  List twoDArrayToList(T[][] twoDArray) { List list = new ArrayList(); for (T[] array : twoDArray) { list.addAll(Arrays.asList(array)); } return list; } 
 for(int i=0;i 

我认为其他技巧是不必要的,因为无论如何,他们会使用这个解决方案。

自java-8

 List collection = Arrays.stream(array) //'array' is two-dimensional .flatMap(Arrays::stream) .collect(Collectors.toList()); 

这可以通过这种方式使用Java 8流API完成:

 String[][] dataSet = new String[][] {{...}, {...}, ...}; List list = Arrays.stream(dataSet) .map(Arrays::asList) .collect(Collectors.toList()); 

基本上,你做三件事:

  • 将2-d数组转换为流
  • 使用Arrays :: asList API将流中的每个元素(应该是一个数组)映射到List中
  • 将流减少为新列表

将其转换为列表的唯一方法是迭代遍历数组并随时构建列表,如下所示:

 ArrayList list = new ArrayList(foosArray.length); for(Foo[] foo: foosArray){ list.add(foo); } 

使用java8“flatMap”来玩。 一种方法可能是遵循

 List collection = Arrays.stream(array).flatMap(Arrays::stream).collect(Collectors.toList()); 

请注意:在将数组转换作为列表进行处理时,原始数组和对象数组之间存在差异。 ie)int []和Integer []

例如)

 int [][] twoDArray = { {1, 2, 3, 4, 40}, {5, 6, 7, 8, 50}, {9, 10, 11, 12, 60}, {13, 14, 15, 16, 70}, {17, 18, 19, 20, 80}, {21, 22, 23, 24, 90}, {25, 26, 27, 28, 100}, {29, 30, 31, 32, 110}, {33, 34, 35, 36, 120}}; List list = new ArrayList(); for (int[] array : twoDArray) { //This will add int[] object into the list, and not the int values. list.add(Arrays.asList(array)); } 

 Integer[][] twoDArray = { {1, 2, 3, 4, 40}, {5, 6, 7, 8, 50}, {9, 10, 11, 12, 60}, {13, 14, 15, 16, 70}, {17, 18, 19, 20, 80}, {21, 22, 23, 24, 90}, {25, 26, 27, 28, 100}, {29, 30, 31, 32, 110}, {33, 34, 35, 36, 120}}; List list = new ArrayList(); for (Integer[] array : twoDArray) { //This will add int values into the new list // and that list will added to the main list list.add(Arrays.asList(array)); } 

致Keppil答案; 你必须使用如何在Java中将int []转换为Integer []将原始数组转换为对象数组?

否则在正常for循环中逐个添加int值。

 int iLength = twoDArray.length; List> listOfLists = new ArrayList<>(iLength); for (int i = 0; i < iLength; ++i) { int jLength = twoDArray[0].length; listOfLists.add(new ArrayList(jLength)); for (int j = 0; j < jLength; ++j) { listOfLists.get(i).add(twoDArray[i][j]); } } 

另请注意,Arrays.asList(array)将给出固定大小的列表; 所以尺寸无法修改 。

另一种技术。

 //converting 2D array to string String temp = Arrays.deepToString(fooArr).replaceAll("\\[", "").replaceAll("\\]", ""); List fooList = new ArrayList<>(Arrays.asList(",")); 
 ArrayList allElelementList = new ArrayList<>(allElelements.length); allElelementList.addAll(Arrays.asList(allElelements)); 

allElelements是二维的