问题
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);
回答1:
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. Integer
→ int
).
See:
- Stream#mapToInt(ToIntFunction)
- IntStream#toArray()
来源:https://stackoverflow.com/questions/58228825/convert-nested-list-of-integers-to-a-two-dimensional-array-using-streams-list