我需要将类型相同的MonthlyExpenses
列表中的所有金额相加。
在我的代码中,我将expenses
和obligations
追加到MonthlyExpenses
的同一列表中。
下面是我的代码:
List<MonthlyExpenses> monthlyExpenses = new ArrayList<MonthlyExpenses>();
List<Expenses> expenses = getExpenses(borrower);
List<Obligations> obligations = getObligations(borrower);
if(expenses!=null){
monthlyExpenses.addAll(createMonthlyExpenses(expenses));
}
if(obligations!=null){
monthlyExpenses.addAll(createMonthlyObligations(obligations));
}
...
public class MonthlyExpenses {
private String type = null;
private BigDecimal amount = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
}
如果执行1st IF statement
,则返回:
class MonthlyExpenses{
type: FOOD
amount: 150.00
}, class MonthlyExpenses{
type: UTILITIES
amount: 250.00
}, class MonthlyExpenses{
type: TRANSPORTATION
amount: 350.00
}, class MonthlyExpenses{
type: CHILD CARE
amount: 450.00
}, class MonthlyExpenses{
type: CREDIT CARDS
amount: 878.00
}, class MonthlyExpenses{
type: Other
amount: 2888.64
}
如果执行2nd IF statement
,则返回:
class MonthlyExpenses{
type: AUTO LOANS
amount: 200.00
}, class MonthlyExpenses{
type: CREDIT CARDS
amount: 300.00
}, class MonthlyExpenses{
type: INSTALLMENT LOANS
amount: 50.00
}, class MonthlyExpenses{
type: ALIMONY/SUPPORT
amount: 75.00
}, class MonthlyExpenses{
type: Other
amount: 10096.87
}
如果类型相等,我如何签入List<MonthlyExpenses>
,并将这些数量相加,然后返回新的列表?
1条答案
按热度按时间omqzjyyz1#
您可以使用
streams
和collectors
来实现此目的:工作方式是对所有费用使用
collect
,按(groupBy
)type
分组,并用作 summing 下游收集器。然后,使用此Map(类型和总金额之间)创建包含所需总费用的对象。下面的类是此Map的一个完整应用程序,供您使用:Complete code on GitHub