如何通过lambda返回以下结果?
int total = 0;
for (User user : userList) {
total += user.getAge();
}
Run Code Online (Sandbox Code Playgroud)
我知道减少使用.new LinkedList<Integer>().stream().reduce(0, (acc, x) -> acc + x)
我想尝试(但失败了).userList.stream().reduce(0, (acc, x) -> acc.getAge() + x.getAge());
您可以使用 mapToInt
useList
.stream()
.mapToInt(User::getAge)
.sum();
Run Code Online (Sandbox Code Playgroud)
如果你真的想使用reduce,这里就是(但我没有看到使用它的一点,因为上面的内容更具可读性)
useList.stream()
.mapToInt(User::getAge)
.reduce(0, (acc, current) -> acc + current);
Run Code Online (Sandbox Code Playgroud)
或者按照Holger @的建议
user.stream()
.reduce(0, (c, user) -> c + user.getAge(), (a, b) -> a + b);
Run Code Online (Sandbox Code Playgroud)