java - 复制 List<List<Integer>>,但有大小限制

标签 java collections

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;
}

我用这个方法来复制列表的列表。有更好的办法吗?

最佳答案

您可以简单地使用streamlimit

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/

相关文章:

c# - 使用索引器从数据存储中检索 Linq to SQL 对象

c# - 在 C# .NET 2.0 中,反向执行 foreach 的简单方法是什么?

java - JPA 和 Hibernate 持久化 @manytoOne 关系

java - "Using Maven 2 dependency tree to get verbose output, which may be inconsistent with actual Maven 3 resolution"

java - 如何在J2ME 中使用HTTP 范围 header ?

Java - 带有代码的 token 流 OAuth 2 E2E

java - 返回 Java 数组与集合

java - Jpa ManyToMany 自引用,无需辅助连接表

java - 在集合上调用方法以添加到另一个集合

java - 如何在 java 8 中使用流过滤两个列表对象并将值设置为新列表