List of List to 2-dimensional string

Viewed 233

I have a dynamic list of list defined by

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

like:

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

in this example it has 2 group of 4 items each but it can have 1 group to n groups dynamically.

Now, I need a 2-dimensional string, so something like:

String[][] data ={{"A", "B", "C", "D"}, {"E", "F", "G", "H"}}

exist a way to convert it easily? If not, how can I create dynamically a 2-dimension String where I know the number of column but not the rows?

3 Answers

Try it like this using streams. It streams the list and converts each inner list to an array and then converts those two arrays to an array of array.

List<List<String>>  list = List.of(
                List.of("A", "B", "C", "D"),
                List.of("E", "F", "G", "H"));
String[][] arr = list.stream()
             .map(lst->lst.stream()
                     .toArray(String[]::new))
             .toArray(String[][]::new);

System.out.println(Arrays.deepToString(arr));

Prints

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

You could also do it this way.

String[][] arr = new String[list.size()][];
for (int i = 0; i < list.size(); i++) {
    arr[i] = list.get(i).toArray(new String[0]);
}

My proposal

private String[][] toMatrix(List<List<String>> listOfLists) {
    int size = listOfLists.size();
    String[][] result = new String[size][];

    for (int i = 0; i < size; i++) {
        List<String> list = listOfLists.get(i);
        result[i] = new String[list.size()];

        for (int j = 0; j < list.size(); j++) {
            result[i][j] = list.get(j);
        }
    }

    return result;
}

This should work:

private static String[][] convert(List<List<String>> listOfLists) {
    var result = new String[listOfLists.size()][];

    var i = 0;
    for (var list : listOfLists) {
        result[i] = new String[list.size()];
        var j = 0;

        for (var elem : list) {
            result[i][j] = elem;
            j++;
        }

        i++;
    }

    return result;
}
Related