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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:45:13  来源:igfitidea点击:

Java8: sum values from specific field of the objects in a list

javafilterjava-8java-stream

提问by mat_boy

Suppose to have a class Obj

假设有一个类 Obj

class Obj{

  int field;
}

and that you have a list of Objinstances, 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 fieldfrom the objects in list lstunder 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

You can try

你可以试试

int sum = list.stream().filter(o->o.field>10).mapToInt(o->o.field).sum();

Like explained here

就像这里解释的一样

回答by Sotirios Delimanolis

You can also collectwith an appropriate summing collector like Collectors#summingInt(ToIntFunction)

您还可以collect使用合适的求和收集器,例如Collectors#summingInt(ToIntFunction)

Returns a Collectorthat 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 Objentity with fieldand getField() method you can use:

在 Java 8 中,对于Obj带有fieldgetField() 方法的实体,您可以使用:

List<Obj> objs ...

Stream<Obj> notNullObjs =
  objs.stream().filter(obj -> obj.getValue() != null);

Double sum = notNullObjs.mapToDouble(Obj::getField).sum();