Convert List of ArrayList of Objects into Object [][]

杀马特。学长 韩版系。学妹 提交于 2019-12-24 06:35:06

问题


Do anyone have an idea how to convert 2 dimension List:

private List<ArrayList<Object>> data = new ArrayList<ArrayList<Object>>();

into array: Object [][] data; ? I noticed that data.asList(new Object[i][j]); is returning only 1 dimension like T[]. Of course j dimension is always constant.


回答1:


You could use a for loop and call toArray() for each inner list.

Object[][] arr = new Object[data.size()][];
int i = 0;
for(ArrayList<Object> list : data){
    arr[i++] = list.toArray();
}

With java-8, you could map each inner list to an array and then construct the resulting array:

Object[][] arr = data.stream().map(List::toArray).toArray(Object[][]::new);



回答2:


As far as I know, you have to loop over all the arrays in the list like this:

Object[][] objs = new Object[data.size()][];
for(int i= 0; i < data.size(); i++)
    objs[i] = data.get(i).toArray();



回答3:


What about using Java8's streams ?

    data.stream()
            .map(il -> il.stream().toArray(size -> new Integer[size]))
// OR THIS  .map(il -> il.toArray(new Integer[0]))
            .toArray(size -> new Integer[size][]);
  1. stream - do something like iterator and goes through all elements (all Lists)
  2. map - transfer element (List) into what you want (Array[]). While List could be streamed you do same, but you could use Arrays
  3. toArray - you transfer you stream and finalize it.

Here is whole Main method with some example data

public static void main(String[] args) {
    List<List<Integer>> data = new ArrayList<>();
    data.add(Arrays.asList(10, 11, 12, 13));
    data.add(Arrays.asList(20, 21, 22, 23));
    Integer[][] result = data.stream()
            .map(il -> il.toArray(new Integer[0]))
            .toArray(size -> new Integer[size][]);
}


来源:https://stackoverflow.com/questions/23324347/convert-list-of-arraylist-of-objects-into-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!