有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

把一个集合分成更小的集合

我有一个集合,我想把它分成更小的集合,大小为x。番石榴也有类似的列表-Lists.partition。但我找不到任何与布景有关的东西。有没有图书馆可以帮我做这件事?如果没有,最好的方法是什么

编辑:目前,我的做法如下:

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

我在用这个Iterables.partition。应该有更好的方法做到这一点,不需要将集合转换为列表,然后再返回集合


共 (1) 个答案

  1. # 1 楼答案

    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);
    }
    

    无论出于何种目的,结果都是随机的。未定义输入集的哪些元素进入哪个输出集,在输出集中,值的顺序是任意的