Rosicleia Frasson
Rosicleia Frasson

Reputation: 123

Copy List<List<Integer>> with limitation of size

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?

Upvotes: 2

Views: 133

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40078

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());

Upvotes: 4

Related Questions