问题
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][]);
- stream - do something like iterator and goes through all elements (all Lists)
- map - transfer element (List) into what you want (Array[]). While List could be streamed you do same, but you could use Arrays
- 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