学习和玩Java8。试图创建一个2D数组。
final List<Integer> row = IntStream.range(0, 3)
.boxed()
.collect(Collectors.toList());
List<List<Integer>> arr2D = IntStream.range(0, 3)
.map(i -> arr2D.add(i, row)); // will not compile如何将行放入2D数组?这是使用Java8的正确方式吗?
发布于 2015-07-22 18:39:22
您的问题提到数组,但您的代码只有列表。如果要生成嵌套列表:
List<List<Integer>> arr2D = IntStream.range(0, 3)
.mapToObj(i -> row)
.collect(Collectors.toList());当然,使用此代码,所有内部列表都将是相同的(即相同的实例)。如果希望每个内部列表都是不同的实例:
List<List<Integer>> arr2D = IntStream.range(0, 3)
.mapToObj(i -> new ArrayList<Integer>(row))
.collect(Collectors.toList());发布于 2015-07-22 18:44:48
解决办法可以是:
List<List<Integer>> lists = IntStream.range(0, 3)
.mapToObj(i -> IntStream.range(0, 3)
.mapToObj(j -> j)
.collect(Collectors.toList()))
.collect(Collectors.toList());https://stackoverflow.com/questions/31571333
复制相似问题