18

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

List<List<String>> list = new ArrayList<>();

list.add(Arrays.asList("a", "b", "c"));
list.add(Arrays.asList("dd"));
list.add(Arrays.asList("eee", "fff"));

I want to make this a String[][]. I've tried the following:

String[][] array = (String[][]) list.toArray();      // ClassCastException

String[][] array = list.toArray(new String[3][3]);   // ArrayStoreException

String[][] array = (String[][]) list.stream()        // ClassCastException
    .map(sublist -> (String[]) sublist.toArray()).toArray();

Is there a way that works? Note that I won't know the size of the list until runtime, and it may be jagged.

1
  • You haven't tried to do it manually with two nested for loops? Commented Nov 4, 2014 at 1:44

3 Answers 3

41

You could do this:

String[][] array = list.stream()
    .map(l -> l.stream().toArray(String[]::new))
    .toArray(String[][]::new);

It creates a Stream<List<String>> from your list of lists, then from that uses map to replace each of the lists with an array of strings which results in a Stream<String[]>, then finally calls toArray(with a generator function, instead of the no-parameter version) on that to produce the String[][].

Sign up to request clarification or add additional context in comments.

3 Comments

How about primitive types like "double[][]" ?
@fuat list.stream() .map(l -> l.stream().mapToDouble(Double::doubleValue).toArray()) .toArray(double[][]::new) if list is a List<List<Double>>. It will throw a NullPointerException if any of the Doubles are null though.
i use this .stream().map(p -> new double[] {p.get(0), p.get(1)}).toArray(double[][]::new) but your solution looks better. thanks
18

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<String> nestedList : list) {
    array[i++] = nestedList.toArray(new String[0]);
}

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

Comments

0

This is the best and most efficient way to convert 2d list to 2d array;

List<List<Integer>>  list2d = new ArrayList<>();
Integer[][] array2d;

array2d = list2d.stream().map(x->x.toArray(new Integer[x.size()])).toArray(Integer[][]::new);

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.