[英]Dividing ArrayList into smaller ArrayLists with specific amount of element
[英]dividing arraylist into multiple arraylists
我的程序根據一天中的時間創建一個5000至60000條記錄的數組列表。 我想將其拆分為盡可能多的數組列表,每個數組列表將具有1000條記錄。 我在網上查看了許多示例並嘗試了一些方法,但遇到了奇怪的問題。 你能給我看看一個例子嗎?
問候!
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.
}
}
您可以使用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;
}
請注意,您必須在此處檢查一次錯誤。 這只是一個快速的偽代碼示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.