1

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
  • Use a loop. And inside this loop, transfor each inner list into an Object[]. Commented Apr 27, 2014 at 14:06

3 Answers 3

4

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 , 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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You very much. It totally solved my problem. I will also try with 1.8 features, It will force me to see new features for sure :)
0

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();

Comments

0

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][]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.