Efficient way to divide a list into lists of n size

前端 未结 14 1295
无人共我
无人共我 2020-11-27 16:59

I have an ArrayList, which I want to divide into smaller Lists of n size, and perform an operation on each. My current method of doing this is

implemented with Array

14条回答
  •  囚心锁ツ
    2020-11-27 17:35

    You'll want to do something that makes use of List.subList(int, int) views rather than copying each sublist. To do this really easily, use Guava's Lists.partition(List, int) method:

    List foos = ...
    for (List partition : Lists.partition(foos, n)) {
      // do something with partition
    }
    

    Note that this, like many things, isn't very efficient with a List that isn't RandomAccess (such as a LinkedList).

提交回复
热议问题