Java:如何将 ArrayList 拆分为多个小的 ArrayList?

标签 java arraylist

如何将一个 ArrayList (size=1000) 拆分为多个相同大小 (=10) 的 ArrayList?

ArrayList<Integer> results;

最佳答案

您可以使用 subList(int fromIndex, int toIndex)以查看原始列表的一部分。

来自 API:

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

例子:

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]"

如果您需要这些截断的列表不是 View ,那么只需从 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!)

关于Java:如何将 ArrayList 拆分为多个小的 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2895342/

相关文章:

java - 将 JsonNode 转换为对象

java - StAX 不检索属性的数据

java - 选择OneToMany查询jpql

java - 为什么框架上没有画绳子?

java - 删除 ArrayList 中的元素时出现 ConcurrentModificationException [使用 iterator.remove()]

java - 将 arraylist 拆分为单独的数组,其中包含导入数据中的各个元素

java - 迭代后检索值

java - 按特定顺序对数组列表进行排序

java - 如何将一个列表分配给另一个列表?

java - 列表列表中的堆算法实现