private static List<List<Integer>> copy(List<List<Integer>> grid, int rows, int columns) {
List<List<Integer> > newGrid = new ArrayList<List<Integer>>();
for(int i = 0; i < rows; i++) {
newGrid.add(new ArrayList<Integer>());
for(int j = 0; j< columns; j++) {
newGrid.get(i).add(grid.get(i).get(j));
}
}
return newGrid;
}
我用这个方法来复制列表的列表。有更好的办法吗?
最佳答案
List<List<Integer>> res = grid.stream()
.map(l->l.stream().limit(columns).collect(Collectors.toList())
.limit(rows)
.collect(Collectors.toList());
或者您也可以使用subList
The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa
List<List<Integer>> res = grid.stream()
.map(l->l.subList(0, columns))
.limit(rows)
.collect(Collectors.toList());
关于java - 复制 List<List<Integer>>,但有大小限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58967384/