【发布时间】:2012-07-16 01:24:18
【问题描述】:
我的程序根据一天中的时间创建一个包含 5000 到 60000 条记录的数组列表。我想将它拆分为尽可能多的数组列表,每个数组列表将有 1000 条记录。我在网上查看了许多示例并尝试了一些方法,但遇到了奇怪的问题。你能给我举个例子吗?
问候!
【问题讨论】:
-
导致您出现问题的代码在哪里?
标签: java
我的程序根据一天中的时间创建一个包含 5000 到 60000 条记录的数组列表。我想将它拆分为尽可能多的数组列表,每个数组列表将有 1000 条记录。我在网上查看了许多示例并尝试了一些方法,但遇到了奇怪的问题。你能给我举个例子吗?
问候!
【问题讨论】:
标签: java
public static <T> Collection<Collection<T>> split(Collection<T> bigCollection, int maxBatchSize) {
Collection<Collection<T>> result = new ArrayList<Collection<T>>();
ArrayList<T> currentBatch = null;
for (T t : bigCollection) {
if (currentBatch == null) {
currentBatch = new ArrayList<T>();
} else if (currentBatch.size() >= maxBatchSize) {
result.add(currentBatch);
currentBatch = new ArrayList<T>();
}
currentBatch.add(t);
}
if (currentBatch != null) {
result.add(currentBatch);
}
return result;
}
这是我们如何使用它(假设电子邮件是一个大的电子邮件地址数组列表:
Collection<Collection<String>> emailBatches = Helper.split(emails, 500);
for (Collection<String> emailBatch : emailBatches) {
sendEmails(emailBatch);
// do something else...
// and something else ...
}
}
emailBatch 会像这样遍历集合:
private static void sendEmails(Collection<String> emailBatch){
for(String email: emailBatch){
// send email code here.
}
}
【讨论】:
您可以使用List 中的subList http://docs.oracle.com/javase/6/docs/api/java/util/List.html#subList 来拆分您的ArrayList。子列表将为您提供原始列表的视图。如果您真的想创建一个与旧列表分开的新列表,您可以执行以下操作:
int index = 0;
int increment = 1000;
while ( index < bigList.size() ) {
newLists.add(new ArrayList<Record>(bigList.subList(index,index+increment));
index += increment;
}
请注意,您必须在此处检查一个错误。这只是一个快速的伪代码示例。
【讨论】:
ArrayLists,每个包含 1000 条记录。不是 5-60 ArrayLists 提供相同数组 5000-60000 条记录的不同视图。
new ArrayList<>(bigList.subList(index, index+increment))。