2015-09-25 35 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); 
} 

对于所有意图和目的,结果是随机的。没有定义哪些输入集合中的哪些元素进入输出集合,并且在输出集合中,这些值将以任意顺序排列。