Java8: sum values from specific field of the objec

2019-01-09 08:15发布

Suppose to have a class Obj

class Obj{

  int field;
}

and that you have a list of Obj instances, i.e. 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)?

4条回答
不美不萌又怎样
2楼-- · 2019-01-09 08:39

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));
查看更多
乱世女痞
3楼-- · 2019-01-09 08:54

Try:

int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();
查看更多
聊天终结者
4楼-- · 2019-01-09 08:58

You can try

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

Like explained here

查看更多
萌系小妹纸
5楼-- · 2019-01-09 08:59

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();
查看更多
登录 后发表回答