问题

如何在相同大小(= 10)的多个ArrayLists中拆分ArrayList(size = 1000)?

ArrayList<Integer> results;

#1 热门回答(264 赞)

你可以使用subList(int fromIndex, int toIndex)获取原始列表的一部分视图。

来自API:

返回指定fromIndex(包含)和toIndex(不包括)之间此列表部分的视图。 (如果fromIndex和toIndex相等,则返回的列表为空。)返回的列表由此列表支持,因此返回列表中的非结构更改将反映在此列表中,反之亦然。返回的列表支持此列表支持的所有可选列表操作。

例:

List<Integer> numbers = new ArrayList<Integer>(
        Arrays.asList(5,3,1,2,9,5,0,7)
    );
    List<Integer> head = numbers.subList(0, 4);
    List<Integer> tail = numbers.subList(4, 8);
    System.out.println(head); // prints "[5, 3, 1, 2]"
    System.out.println(tail); // prints "[9, 5, 0, 7]"
    Collections.sort(head);
    System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7]"
    tail.add(-1);
    System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7, -1]"

如果你需要这些切碎列表不是视图,那么只需从subList创建一个新的List。以下是将这些内容放在一起的示例:

// chops a list into non-view sublists of length L
static <T> List<List<T>> chopped(List<T> list, final int L) {
    List<List<T>> parts = new ArrayList<List<T>>();
    final int N = list.size();
    for (int i = 0; i < N; i += L) {
        parts.add(new ArrayList<T>(
            list.subList(i, Math.min(N, i + L)))
        );
    }
    return parts;
}


List<Integer> numbers = Collections.unmodifiableList(
    Arrays.asList(5,3,1,2,9,5,0,7)
);
List<List<Integer>> parts = chopped(numbers, 3);
System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]"
parts.get(0).add(-1);
System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]"
System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!)

#2 热门回答(165 赞)

你可以将Guavalibrary添加到你的项目中,并使用Lists.partition方法,例如

List<Integer> bigList = ...
List<List<Integer>> smallerLists = Lists.partition(bigList, 10);

#3 热门回答(43 赞)

Apache Commons Collections 4ListUtils类中有分离方法。以下是它的工作原理:

import org.apache.commons.collections4.ListUtils;
...

int targetSize = 100;
List<Integer> largeList = ...
List<List<Integer>> output = ListUtils.partition(largeList, targetSize);

原文链接