This post will discuss how to convert a List of Lists to a two-dimensional primitive or Object array in Java.

There is no straightforward way to convert a List of Lists to a two-dimensional array. However, introduction of Stream API in Java 8 made this task a little simpler:

1. Stream API

The standard solution to convert a List of Lists to a two-dimensional primitive array in Java is using Stream API. The idea is to get a stream of the list of lists and use map() to replace each of the nested lists with the corresponding single-dimensional array. Then, finally call toArray() with a generator to produce the two-dimensional primitive array.

Download  Run Code

Output:

[[1, 3, 2], [1, 2, 2], [1, 2]]

 
A similar idea can be applied to the list of lists of Wrapper class to get the two-dimensional array, as shown below:

Download  Run Code

Output:

[[A, B, C], [B, D], [E, F]]

 
Here’s an alternative version of the above code that uses List’s toArray() method:

Download  Run Code

Output:

[[A, B, C], [B, D], [E, F]]

2. Using Loops

Before Java 8, you can create a two-dimensional array of the same size as that of the given list and use a for-loop to fill each array row with the results of the calling toArray() method upon each of the nested lists.

Download  Run Code

Output:

[[A, B, C], [B, D], [E, F]]

That’s all about converting a List of Lists to a two-dimensional array in Java.