Convert List<List<Integer>> to int[][] in Java 8

Viewed 283

I am looking to convert the List<List<Integer>> into int[][] in Java 8. Any quick pointers?

I tried something like below, but I need int[][].

List<Integer> flat = arr.stream()
                        .flatMap(List::stream)
                        .collect(Collectors.toList());
1 Answers

You can map to int the inner lists and collect them into int arrays, then collect the outer list as a 2D array:

int[][] flat = arr.stream()
        .map(a -> a.stream().mapToInt(Integer::intValue).toArray())
        .toArray(int[][]::new);
Related