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

假设有一个类 Obj:

class Obj {
int field;
}

你有一个 Obj实例的列表,也就是 List<Obj> lst

现在,我如何在过滤条件下(例如,对于一个对象 o,条件是 o.field > 10)找到来自列表 lst中的对象的 int 字段 field的值之和?

153106 次浏览

Try:

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

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)

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.

For example

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

In Java 8 for an Obj entity with field and getField() method you can use:

List<Obj> objs ...


Double sum = objs.stream()
.filter(Objects::notNull);
.mapToDouble(Obj::getField)
.sum();

You can do this method: "IntSummaryStatistics"

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