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

时间:2012-07-12 08:23:59

标签: java

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

12 个答案:

答案 0 :(得分:32)

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

  

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

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

答案 1 :(得分:13)

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

答案 2 :(得分:8)

for(int i=0;i<m;i++)
    for(int j=0;j<n;j++)
        yourList.add(foosArray[i][j]);

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

答案 3 :(得分:5)

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

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

基本上,你做了三件事:

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

答案 4 :(得分:3)

使用java8&#34; flatMap&#34;玩耍。一种方法可能是

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

答案 5 :(得分:2)

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

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

答案 6 :(得分:1)

  

请注意:在作为列表处理数组转换时,原始数组和Object数组之间存在差异。即)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的回答;你必须使用How to convert int[] to Integer[] in Java?

将原始数组转换为对象数组

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

int iLength = twoDArray.length;
List<List<Integer>> 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)将提供fixed-size list; so size cannot be modified

答案 7 :(得分:0)

另一种技术。

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

答案 8 :(得分:0)

ArrayList<Elelement[]> allElelementList = new ArrayList<>(allElelements.length);
    allElelementList.addAll(Arrays.asList(allElelements));

allElelements是二维的

答案 9 :(得分:0)

这是将int的2D数组(即原始数据类型)转换为列表的分步解决方案。解释在代码注释中。

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Temp {
    public static void main(String... args) {
        System.out.println("Demo...");
        int [] [] twoDimArray = new int[][]{
                {1,2}, {3,5}, {8,15}
        };

        List< List<Integer> > nestedLists =
                Arrays.
                //Convert the 2d array into a stream.
                stream(twoDimArray).
                //Map each 1d array (internalArray) in 2d array to a List.
                map(
                        //Stream all the elements of each 1d array and put them into a list of Integer.
                        internalArray -> Arrays.stream(internalArray).boxed().collect(Collectors.toList()
                    )
        //Put all the lists from the previous step into one big list.
        ).collect(Collectors.toList());

        nestedLists.forEach(System.out::println);
        
    }
}

输出:

Demo...
[1, 2]
[3, 5]
[8, 15]

答案 10 :(得分:0)

让我们添加一些原始类型数组处理。但是您可以将参数传递给任何对象。方法正确处理为 int[][] as Object[][]:

 public <T, E> List<E> twoDArrayToList(T twoDArray) {

   if (twoDArray instanceof int[][])
     return Arrays.stream((int[][])twoDArray)
                  .flatMapToInt(a->Arrays.stream(a))
                  .mapToObj(i->(E)Integer.valueOf(i))
                  .collect(Collectors.toList());

   //… processing arrays of other primitive types 

   if (twoDArray instanceof Object[][])
        return Arrays.stream((E[][])twoDArray)
               .flatMap(Arrays::stream)
               .collect(Collectors.toList());

   return null; // better to throw appropriate exception 
                // if parameter is not two dimensional array
}

答案 11 :(得分:0)

例如

Integer[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 9, 8, 9 }, };
        
List<List<Integer>> arr = Arrays.stream(a)
                .map(Arrays::asList)
                .collect(Collectors.toList());