Java8:总结列表中对象的特定字段的值 [英] Java8: sum values from specific field of the objects in a list
本文介绍了Java8:总结列表中对象的特定字段的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Obj {
int field;
$ / code>
,并且您有一个 Obj
实例,即
List< Obj>现在,我怎么能在Java8中找到int字段值的总和
字段从列表
lst
中的对象在过滤条件下(例如,对象 o
标准是 o.field> 10
)?
解决方案
可以做到:
$ b $ pre $ int sum = lst.stream()。filter(o - > o.getField()> 10) .mapToInt(o - > o.getField())。sum();
或(使用方法引用)
<$ p () - > 10).mapToInt(Obj :: getField).sum(); $ p> int sum = lst.stream()。filter(o - > o.getField
Suppose to have a class Obj
class Obj{
int field;
}
and that you have a list of Obj
instances, i.e. List<Obj> lst
.
Now, how can I find in Java8 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
)?
解决方案
You can do
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();
or (using Method reference)
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();
这篇关于Java8:总结列表中对象的特定字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文