使用流将嵌套的整数列表转换为二维数组(List< List< Integer>>-> int [] []) [英] Convert Nested List of Integers to a two dimensional array using Streams ( List<List<Integer>> -> int[][] )
本文介绍了使用流将嵌套的整数列表转换为二维数组(List< List< Integer>>-> int [] [])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我搜索了类似的问题,但只找到了不适用于这种情况的对象String:
I searched for similar questions but I found only for the object String which dont apply to this case:
想使用流将List<List<Integer>> list
转换为int[][] array
到目前为止,我知道了:
So far I got this:
int[][] array= list.stream().map(List::toArray)...
我将发现的其他类似问题作为基础.但是这些使用String并且不能使它适用于Integers-> int:
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);
推荐答案
您只需要对String[][]
解决方案进行一些修改:
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);
mapToInt(i -> i)
正在取消每个Integer
的装箱(即Integer
→int
).
The mapToInt(i -> i)
is unboxing each Integer
(i.e. Integer
→ int
).
请参阅:
这篇关于使用流将嵌套的整数列表转换为二维数组(List< List< Integer>>-> int [] [])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文