我知道我可以用以下语句填充普通的vetor/list中的一些zeros:
double[][] list = new double[10][10]; // It will automatically inserts 0's in all positions.
List<Double> list1 = new ArrayList(new ArrayList(Collections.nCopies(10, 0d))); // Also我想做同样的事情,但使用2D列表,这是可能的吗?
List<List<Double>> list2 = new ArrayList();
// It doesn't work -> List<List<Double>> list2 = new ArrayList(new ArrayList(Collections.nCopies(10, 0d)));顺便说一下,我想避免使用显式循环。
发布于 2016-03-31 13:27:41
下面的呢?
Stream.generate(() -> new ArrayList<Double>(Collections.nCopies(10, 0.0)))
.limit(10)
.collect(Collectors.toList());发布于 2016-03-31 13:23:51
List<Double> list1 = new ArrayList(new ArrayList(Collections.nCopies(10, 0d)));这是多余的。将列表传递给分段构造函数。这就够了:
List<Double> list1 = new ArrayList(Collections.nCopies(10, 0d));使用2D列表,您可以这样做:
List<List<Double>> list2 = new ArrayList(Collections.nCopies(10, new ArrayList(Collections.nCopies(10, 0d))));但是要小心,列表包含了对同一列表的引用的十倍。
如果您希望有不同的列表,并避免和显式的for循环,则可以使用隐式for循环和java 8。
List<List<Double>> list2 = new ArrayList();
Collections.nCopies(10, new ArrayList(Collections.nCopies(10, 0d))).forEach((list) -> list2.add(new ArrayList(list)));发布于 2016-03-31 13:25:21
例如,流:
List<List<Double>> list2 = IntStream.range(0, 10)
.mapToObj(i -> new ArrayList<Double>(Collections.nCopies(10, 0d)))
.collect(Collectors.toList());它也会迭代,但隐式地。
https://stackoverflow.com/questions/36334609
复制相似问题