[英]java lambda:How to count total items in a list?
How can I return the following result by lambda? 如何通过lambda返回以下结果?
int total = 0;
for (User user : userList) {
total += user.getAge();
}
I know reduce's use. 我知道减少使用。
new LinkedList<Integer>().stream().reduce(0, (acc, x) -> acc + x)
I want to try(but failed). 我想尝试(但失败了)。
userList.stream().reduce(0, (acc, x) -> acc.getAge() + x.getAge());
You can use mapToInt
您可以使用
mapToInt
useList
.stream()
.mapToInt(User::getAge)
.sum();
If you really wanted to use reduce
, here it is (but I don't see a point in using it as the above is more readable) 如果您真的想使用
reduce
,那么就在这里(但我看不出使用它的意义,因为上面的内容更具可读性)
useList.stream()
.mapToInt(User::getAge)
.reduce(0, (acc, current) -> acc + current);
Or as suggested by Holger@ 或按照Holger @的建议
user.stream()
.reduce(0, (c, user) -> c + user.getAge(), (a, b) -> a + b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.