【发布时间】:2022-02-02 22:22:36
【问题描述】:
我有一个流,其中每个对象都由一个唯一的 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(Predicate, Collector)来划分为集合而不是列表。 -
旁注:条件表达式也适用于这种情况:
foos.forEach(f -> (f.free >= 0? positives: negatives).add(f.id));
标签: java java-stream