将二维数组int[][]转换成一个嵌套的List<List<Integer>> 的形式
代码如下
public static List<List<Integer>> generate(int numRows) {
int[][] ints = new int[numRows][numRows];
for (int i = 0; i < numRows; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
ints[i][j] = 1;
} else {
ints[i][j] = ints[i - 1][j - 1] + ints[i - 1][j];
}
}
}
//todo
}}
最后需要 List<List> 这种结果集,采用lambda来实现
实现一
List<List<Integer>> collect = Arrays.stream(ints).map(l -> {
return Arrays.stream(l)
.boxed().collect(Collectors.toList());
}).collect(Collectors.toList());
实现二
List<List<int[]>> collect2 = Arrays.stream(ints).map(Arrays::asList)
.collect(Collectors.toList());
会发现 实现二返回的并不是我们需要的形式,实现一才是我们需要的,原因是需要进行一次装箱即可,采用实现一即可
如果需要合并成一个List的形式需要用到 flatMap拆分流
List<Integer> collect = Arrays.stream(ints).flatMap(l -> {
return Arrays.stream(l).boxed();
}).collect(Collectors.toList());