考虑以下类别:
public class PersonalExpense {
private String name;
private int currentExpenses;
...
我该如何编写与第一种方法(getRemainingCompanyBalance)相同的Java流“管道”。此代码将导致错误。
该列表包含每个部门的单独列表。子列表中的每个条目都是该类的一个实例。名称/费用:
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;
}