gpt4 book ai didi

java - 收集java流中字段的总和

转载 作者:行者123 更新时间:2023-12-02 10:46:44 26 4
gpt4 key购买 nike

考虑以下类:

public class PersonalExpense {
private String name;
private int currentExpenses;

...

我如何编写一个java流“管道”,其工作方式与第一个方法(getRemainingCompanyBalance)相同。此代码会导致错误。

the list contains separate lists for each department. each entry in the sub-list is an instance of the class. name/cost:

de#1first"/9900, de#1second"/8700, de#2first"/8500, de#2second"/10000, de#3first"/7800, de#3second"/6900

    private static long getRemainingCompanyBalance ( long initialBalance, List<ArrayList<PersonalExpense>> total) {
long remainingBalance = initialBalance;
for (List<PersonalExpense> departmentExpense : total) {
for (PersonalExpense personalExpense : departmentExpense) {
System.out.println(personalExpense.getName());
remainingBalance = remainingBalance - personalExpense.getCurrentExpenses();
}
}
return remainingBalance;
}

public static long getRemainingCompanyBalanceLambda ( long initialBalance, List<ArrayList<PersonalExpense>> total) {
long remainingBalance = initialBalance;


Integer sum = total
.stream()
.flatMap(Collection::stream)
.filter(pe -> pe instanceof PersonalExpense)
.map (pe -> (PersonalExpense) pe)
.collect(Collectors.toList())
.mapToInt(PersonalExpense::getCurrentExpenses)
.sum();


return remainingBalance -= sum;
}

}

我正在尝试收取费用,然后从余额中减去它们

最佳答案

public static long getRemainingCompanyBalanceLambda ( long initialBalance, List<ArrayList<PersonalExpense>> total) {

int sum = total.stream()
.flatMap(List::stream)
.mapToInt(PersonalExpense::getCurrentExpenses)
.sum();

return initialBalance - sum;

}

关于java - 收集java流中字段的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52499140/

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