【问题标题】:How to divide a stream by object fields into two sets?如何按对象字段将流分成两组?
【发布时间】:2022-02-02 22:22:36
【问题描述】:

我有一个流,其中每个对象都由一个唯一的 ID 标识。 此外,每个对象都有一个正或负的Free 值。

我想将此流分成两个集合,其中一个包含 idsFree 值为正数,另一个包含其余部分。

但我发现以下方法不是正确的方法,因为我正在收集流之外的列表。

class Foo {
    int free;
    long id;
}

public Tuple2<Set<Long>, Set<Long>> findPositiveAndNegativeIds() {
    Set<Long> positives = new HashSet<>();
    Set<Long> negatives = new HashSet<>();

    foos.stream()
            .forEach(f -> {
                if (f.free >= 0) positigves.add(f.id);
                else negatives.add(f.id);
            });
            
    return Tuple2.tuple(positives, negatives);
}

partitionBy() 或类似的方法可以做得更好吗?

【问题讨论】:

标签: java java-stream


【解决方案1】:

您确实可以使用partitioningBy。您可以在第二个参数中指定如何处理每个分区。

var map = foos.stream().collect(Collectors.partitioningBy(
    foo -> foo.free >= 0, // assuming no 0
    // for each partition, map to id and collect to set
    Collectors.mapping(foo -> foo.id, Collectors.toSet())
));

map.get(true) 将为您提供ids 与正frees 的集合,map.get(false) 将为您提供ids 与负frees 的集合。

【讨论】:

  • 我已经在输入相同的代码,但你打败了我;)
  • 那是丢失的照片!
  • 很遗憾,无法立即接受答案。但我现在可以了。+
猜你喜欢
  • 2020-05-22
  • 1970-01-01
  • 2021-08-28
  • 2023-01-25
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多