我有一个流,其中每个对象都由一个唯一的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)
将为您获得具有正free
s的id
s的集合,map.get(false)
将为您获取具有负free
s的ids
的集合。