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

I made this method to copy a list of list. Is there a better way?

Aditya
  • 2,148
  • 3
  • 21
  • 34
  • Does this answer your question? [How to clone ArrayList and also clone its contents?](https://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents) – Smile Nov 21 '19 at 04:40
  • You are basically looking for a deep copy. This is a more generic way of doing the same where even if your object is more complex it will work - https://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object-in-java – Aditya Nov 21 '19 at 04:54

1 Answers1

4

You can simple use the stream with limit

List<List<Integer>> res = grid.stream()
                              .map(l->l.stream().limit(columns).collect(Collectors.toList())
                              .limit(rows)
                              .collect(Collectors.toList());

Or you can also use 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());
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98