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



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

我想把这个流分成两个集合,其中一个包含ids,其Free值为正,另一个包含其余的

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

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()或类似的方法,这能做得更好吗?

您确实可以使用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)将为您获得具有正frees的ids的集合,map.get(false)将为您获取具有负frees的ids的集合。

最新更新