How to convert a List<List<String>> to Object[][]

I have a method which builds a List<List<String>> object. I need to convert this list to type Object[][] and return it. I couldn't do this, when I add an Object[] to a list all the array elements are added as individual objects.

List<Object[]> list = new ArrayList<Object[]>();
list.add(new Object[2]{"A", "B"});
return list.toArray();

From the above example, return list.toArray() is returning Object[] not Object[][] though it was declared as List<Object[]>;

Please help to get Object[][] from List<List<String>>?

Upvotes: 1

Views: 116

Answers (2)

Mureinik
Mureinik

Reputation: 311053

The easiest approach may be to stream the list, and handle sub-list individually:

List<List<String>> list = /* something */
Object[][] result = 
    list.stream()
        .map(List::toArray)
        .toArray(Object[][]::new);

Upvotes: 6

XtremeBaumer
XtremeBaumer

Reputation: 6435

Simply specify the array type you want to convert it to.

List<Object[]> list = new ArrayList<Object[]>();
list.add(new Object[] { "A", "B" });
list.add(new Object[] { "C", "D" });
Object[][] o = list.toArray(new Object[][] {});

for (Object[] o1 : o) {
    for (Object o2 : o1) {
        System.out.print(o2 + " ");
    }
    System.out.println();
}

This codes output is:

A B 
C D 

Upvotes: 2

Related Questions