如何按对象字段将流分为两组?

mem*_*und 1 java java-stream

我有一个流,其中每个对象都由唯一的 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);
}
Run Code Online (Sandbox Code Playgroud)

partitionBy()可以通过某种方式或类似方式做得更好吗?

Swe*_*per 6

你确实可以使用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())
));
Run Code Online (Sandbox Code Playgroud)

map.get(true)id将为您提供带有正 s 的 s集合free,并将为您提供带有负s 的map.get(false)集合。idsfree