2015-09-25 65 views
0

我有一個集合,我想將它分成更小的集合x。番石榴有類似的名單 - Lists.partition。但是我找不到與套裝有關的任何東西。有沒有可以幫助我做這件事的圖書館?如果不是,將一組分成較小組的最好方法是什麼?將一個集合劃分成更小的集合 - Java

編輯:目前,我做如下:

int x = 10; 
Set<String> stringSet = createHashSet(); 
for (List<String> partition : Iterables.partition(stringSet, x) { 
    doSomething(new HashSet<>(partition)); 
} 

我使用這個Iterables.partition。應該有更好的方法來做到這一點,它不涉及將設置轉換爲列表,然後返回到一個集合。

+0

什麼是您的分區邏輯? –

+0

'Set'由定義無序,所以存在於Guava中的'List'的分區邏輯將不適用。你需要爲此自己創建一些東西,具體取決於'Set'實現類('hash','tree'等等。) – Kon

+0

Java 8? http://stackoverflow.com/questions/29095967/splitting-list-into-sublists-along-elements –

回答

0
Set<Integer> input = /*defined elsewhere*/; 
int x = 10; 

List<Set<Integer>> output = new ArrayList<>(); 
Set<Integer> currSet = null; 
for (Integer value : input) { 
    if (currSet == null || currSet.size() == x) 
     output.add(currSet = new HashSet<>()); 
    currSet.add(value); 
} 

對於所有意圖和目的,結果是隨機的。沒有定義哪些輸入集合中的哪些元素進入輸出集合,並且在輸出集合中,這些值將以任意順序排列。