本文介绍了Java:如何将一个 ArrayList 拆分为多个小 ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将一个 ArrayList (size=1000) 拆分为多个相同大小 (=10) 的 ArrayList?
How can I split an ArrayList (size=1000) in multiple ArrayLists of the same size (=10) ?
ArrayList<Integer> results;
推荐答案
您可以使用 subList(int fromIndex, int toIndex)
以查看原始列表的一部分.
You can use subList(int fromIndex, int toIndex)
to get a view of a portion of the original list.
来自 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
.以下是将其中一些内容组合在一起的示例:
If you need these chopped lists to be NOT a view, then simply create a new List
from the subList
. Here's an example of putting a few of these things together:
// 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!