Jae Jarabe Jae Jarabe - 3 months ago 15
Java Question

List<List<Object>> to String[][]. Is there any method?

I want to convert this

final List <List<Object>> datavalues = new ArrayList<>();
into a 2D String array like this
String[][]
.

Answer

In Java 8 you can do

List<List<Object>> values = ...
String[][] valArr = values.stream()
                          .map(l -> l.stream()
                                     .map(e -> e.toString())
                                     .toArray(n -> new String[n]))
                          .toArray(n -> new String[n][]);

As @bohemian points out you can use other lambda forms with

String[][] valArr = values.stream()
                          .map(l -> l.stream()
                                     .map(Object::toString)
                                     .toArray(String[]::new))
                          .toArray(String[][]::new);

The problem I have with :: forms is they can be cooler but more obscure as to what they are doing.

In Java 7, you have to use loops.

Comments