假设有一个类 Obj:
Obj
class Obj { int field; }
你有一个 Obj实例的列表,也就是 List<Obj> lst。
List<Obj> lst
现在,我如何在过滤条件下(例如,对于一个对象 o,条件是 o.field > 10)找到来自列表 lst中的对象的 int 字段 field的值之和?
o
o.field > 10
lst
field
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)
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
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();