Java8:对列表中对象的特定字段的值求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23110853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java8: sum values from specific field of the objects in a list
提问by mat_boy
Suppose to have a class Obj
假设有一个类 Obj
class Obj{
int field;
}
and that you have a list of Obj
instances, i.e. List<Obj> lst
.
并且您有一个Obj
实例列表,即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
)?
现在,我如何在 Java8 中使用流找到过滤条件下field
列表中对象的 int 字段值的总和lst
(例如,对于对象o
,条件是o.field > 10
)?
采纳答案by Aniket Thakur
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();
回答by JeanValjean
Try:
尝试:
int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();
回答by Pawe? ?wik
回答by Sotirios Delimanolis
You can also collect
with an appropriate summing collector like Collectors#summingInt(ToIntFunction)
您还可以collect
使用合适的求和收集器,例如Collectors#summingInt(ToIntFunction)
Returns a
Collector
that produces the sum of a integer-valued function applied to the input elements. If no elements are present, the result is 0.
返回一个
Collector
产生应用于输入元素的整数值函数的总和。如果不存在元素,则结果为 0。
For example
例如
Stream<Obj> filtered = list.stream().filter(o -> o.field > 10);
int sum = filtered.collect(Collectors.summingInt(o -> o.field));
回答by Zon
In Java 8 for an Obj
entity with field
and getField() method you can use:
在 Java 8 中,对于Obj
带有field
getField() 方法的实体,您可以使用:
List<Obj> objs ...
Stream<Obj> notNullObjs =
objs.stream().filter(obj -> obj.getValue() != null);
Double sum = notNullObjs.mapToDouble(Obj::getField).sum();