简体   繁体   English

Java8:对列表中对象的特定字段的值求和

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

Suppose to have a class Obj假设有一个类 Obj

class Obj{

  int field;
}

and that you have a list of Obj instances, ie List<Obj> lst .并且您有一个Obj实例List<Obj> lst ,即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 (eg for an object o , the criterion is o.field > 10 )?现在,如何在 Java8 中使用流在过滤条件下从列表lst的对象中找到 int 字段field的值的总和(例如,对于对象o ,条件是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();

You can try你可以试试

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

Like explained here就像这里解释的一样

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.返回一个Collector ,它生成应用于输入元素的整数值函数的总和。 If no elements are present, the result is 0.如果不存在元素,则结果为 0。

For example例如

Stream<Obj> filtered = list.stream().filter(o -> o.field > 10);
int sum = filtered.collect(Collectors.summingInt(o -> o.field));

尝试:

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

In Java 8 for an Obj entity with field and getField() method you can use:在 Java 8 中,对于带有field和 getField() 方法的Obj实体,您可以使用:

List<Obj> objs ...

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

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

您可以执行此方法:“IntSummaryStatistics”

IntSummaryStatistics insum = li.stream().filter(v-> v%2==0).mapToInt(mapper->mapper).summaryStatistics();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM