gpt4 book ai didi

java lambda :How to count total items in a list?

转载 作者:行者123 更新时间:2023-12-01 07:18:08 25 4
gpt4 key购买 nike

如何通过 lambda 返回以下结果?

int total = 0;
for (User user : userList) {
total += user.getAge();
}

我知道reduce的用途。 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();

如果你真的想使用reduce,这里就是(但我不认为使用它有什么意义,因为上面的代码更具可读性)

useList.stream()
.mapToInt(User::getAge)
.reduce(0, (acc, current) -> acc + current);

或者按照 Holger@ 的建议

user.stream()
.reduce(0, (c, user) -> c + user.getAge(), (a, b) -> a + b);

关于java lambda :How to count total items in a list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50790244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com