Convert nested list to 2d array

后端 未结 4 1806
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 19:07

I\'m trying to convert a nested list into a 2d array.

List> list = new ArrayList<>();

list.add(Arrays.asList(\"a\", \"b\", \"         


        
4条回答
  •  [愿得一人]
    2020-12-09 19:59

    There is no simple builtin way to do what you want because your list.toArray() can return only array of elements stored in list which in your case would also be lists.

    Simplest solution would be creating two dimensional array and filling it with results of toArray from each of nested lists.

    String[][] array = new String[list.size()][];
    
    int i = 0;
    for (List nestedList : list) {
        array[i++] = nestedList.toArray(new String[nestedList.size()]);
    }
    

    (you can shorten this code if you are using Java 8 with streams just like Alex did)

提交回复
热议问题