我的程序根據一天中的時間創建一個5000到60000個記錄的數組列表。我想將它分割成儘可能多的arraylist,每個arraylist將有1000條記錄。我在網上查了很多例子,並嘗試了一些東西,但我遇到了奇怪的問題。你能告訴我一個這樣的例子嗎?將arraylist分爲多個arraylist
問候!
我的程序根據一天中的時間創建一個5000到60000個記錄的數組列表。我想將它分割成儘可能多的arraylist,每個arraylist將有1000條記錄。我在網上查了很多例子,並嘗試了一些東西,但我遇到了奇怪的問題。你能告訴我一個這樣的例子嗎?將arraylist分爲多個arraylist
問候!
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;
}
下面是我們如何使用它(假設電子郵件的一個大的ArrayList的電子郵件地址:
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.
}
}
它看起來像它的工作原理,但我怎麼會從收集的數據中提取?我以前從未使用過集合。 – Arya 2012-07-16 04:27:13
你有。 :) ArrayList是一個集合。很可能你會想要遍歷集合。我已經添加了一個示例用法。 – 2012-07-16 12:17:33
您可以使用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;
}
注意你就會有一個錯誤在這裏檢查過。這只是一個快速的僞代碼示例。
哪裏代碼導致你的問題? – Jeffrey 2012-07-16 01:24:39