【问题标题】:Divide a set into smaller sets - Java将一个集合分成更小的集合 - Java
【发布时间】:2015-12-23 20:02:46
【问题描述】:

我有一个集合,我想将它分成大小为 x 的较小集合。 Guava 有类似的列表 - Lists.partition。但我找不到与 Sets 相关的任何内容。有没有图书馆可以帮助我做到这一点?如果不是,将一个集合分成更小的集合的最佳方法是什么?

编辑:目前,我这样做如下:

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

我正在使用这个Iterables.partition。应该有更好的方法来做到这一点,它不涉及将集合转换为列表,然后再转换回集合。

【问题讨论】:

  • 你的分区逻辑是什么?
  • Set 根据定义是无序的,因此 Guava 中存在的List 的分区逻辑将不适用。您需要为此自己创建一些东西,具体取决于Set 实现类(hashtree 等)
  • @SotiriosDelimanolis - 我不需要任何特殊的分区逻辑。
  • @Kon - 我有一个 HashSet。我只是想把它分成更小的集合并分批处理。

标签: java set guava


【解决方案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);
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 2015-02-26
    • 2023-03-07
    相关资源
    最近更新 更多