0

I searched for similar questions but I found only for the object String which dont apply to this case:

Want to convert List<List<Integer>> list to int[][] array using streams

So far I got this:

int[][] array= list.stream().map(List::toArray)...

I used as a base other similar questions I found. But these use String and can't make it work for Integers->int:

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

// Example with String 2:    
    final List<List<String>> list = ...;
    final String[][] array = list.stream().map(List::toArray).toArray(String[][]::new);
Naman
  • 27,789
  • 26
  • 218
  • 353
jpincz
  • 146
  • 8

1 Answers1

5

You only need to make a few modifications to the String[][] solution:

List<List<Integer>> lists = ...;
int[][] arrays = lists.stream()                                // Stream<List<Integer>>
        .map(list -> list.stream().mapToInt(i -> i).toArray()) // Stream<int[]>
        .toArray(int[][]::new);

The mapToInt(i -> i) is unboxing each Integer (i.e. Integerint).

See:

Slaw
  • 37,820
  • 8
  • 53
  • 80