对列表中对象的特定字段的值求和 [英] Sum values from specific field of the objects in a list
本文介绍了对列表中对象的特定字段的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设有一个 Obj
类:
class Obj {
int field;
}
...并且您有一个 Obj
实例列表,即 List
.
...and that you have a list of Obj
instances, i.e. List<Obj> lst
.
现在,我如何使用流从过滤条件下的列表 lst
中的对象中找到 int 字段 field
o
,标准是o.field > 10
)?
Now, how can I find with streams the sum of the values of the int fields field
from the objects in list lst
under a filtering criterion (e.g. for an object o
, the criterion is o.field > 10
)?
推荐答案
你可以做
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();
或(使用方法参考)
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();
这篇关于对列表中对象的特定字段的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文