我有一个从数据库List
中Item
获取的。
我做类似的事情:
List<Item> list;
list.stream()
.filter( i -> i.condition() )
.mapToLong( Item::asLong )
.sum()
;
现在,我想知道过滤器是否过滤掉了某些东西,因此可以从不再需要它的数据库中删除它。
我可以做:
List<Item> list2 = list.stream()
.filter( i -> i.condition() )
.collect( Collectors.toList() )
;
int theSizeIWant = list2.size();
list2.stream().mapToLong( Item::asLong )
.sum()
;
但我想知道是否有一个不需要创建中间列表的更优雅的解决方案。
一种可能的解决方案是用谓词对Stream进行分区并求和。分区使用进行partitioningBy(predicate, downstream)
。在这种情况下,谓词将是您的过滤函数,而下游收集器将是summingLong
对这些值求和。
public static void main(String[] args) {
List<Item> list = new ArrayList<>();
Map<Boolean, Long> map =
list.stream()
.collect(Collectors.partitioningBy(
Item::condition,
Collectors.summingLong(Item::asLong)
));
long sumWithTrueCondition = map.get(true);
long sumWithFalseCondition = map.get(false);
}
映射将包含谓词为true
(resp。false
)和true
键(resp。false
)的总和。
这样,如果已将某些内容过滤掉,sumWithTrueCondition
则将严格大于0。此外,您可以通过将sumWithTrueCondition
和相加来获得总和sumWithFalseCondition
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句