如何按对象字段将流分成两组?
How to divide a stream by object fields into two sets?
我有一个流,其中每个对象都由唯一的 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)
会给你一组 id
正数 free
s,map.get(false)
会给你一组 ids
负数free
s.
我有一个流,其中每个对象都由唯一的 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)
会给你一组 id
正数 free
s,map.get(false)
会给你一组 ids
负数free
s.