2012-07-16 93 views
0

我的程序根據一天中的時間創建一個5000到60000個記錄的數組列表。我想將它分割成儘可能多的arraylist,每個arraylist將有1000條記錄。我在網上查了很多例子,並嘗試了一些東西,但我遇到了奇怪的問題。你能告訴我一個這樣的例子嗎?將arraylist分爲多個arraylist

問候!

+1

哪裏代碼導致你的問題? – Jeffrey 2012-07-16 01:24:39

回答

2
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. 
    } 
} 
+0

它看起來像它的工作原理,但我怎麼會從收集的數據中提取?我以前從未使用過集合。 – Arya 2012-07-16 04:27:13

+0

你有。 :) ArrayList是一個集合。很可能你會想要遍歷集合。我已經添加了一個示例用法。 – 2012-07-16 12:17:33

1

您可以使用ListsubListhttp://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; 
} 

注意你就會有一個錯誤在這裏檢查過。這只是一個快速的僞代碼示例。

+0

我認爲OP希望5-60個單獨的ArrayList包含1000條記錄,而不是5-60個ArrayList,它提供5000-60000條記錄的同一個數組的不同視圖 – Jeffrey 2012-07-16 01:31:04

+0

好點,我已更新我的代碼以反映這一點。 – 2012-07-16 01:39:22

+0

該代碼不會編譯。我認爲你的意思是'新的ArrayList <>(bigList.subList(index,index + increment))''。 – Jeffrey 2012-07-16 01:42:40