java 遍历列表并对类型相同的所有金额求和

w51jfk4q  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(319)

我需要将类型相同的MonthlyExpenses列表中的所有金额相加。
在我的代码中,我将expensesobligations追加到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>,并将这些数量相加,然后返回新的列表?

omqzjyyz

omqzjyyz1#

您可以使用streamscollectors来实现此目的:

private static List<MonthlyExpense> createMonthlyExpenses(List<MonthlyExpense> expenses) {
        Map<String, Double> sums = expenses.stream()
                .collect(Collectors.groupingBy(
                            MonthlyExpense::getType, 
                            Collectors.summingDouble(MonthlyExpense::getAmount))
        );
        return sums.entrySet().stream()
                .map(entry -> new MonthlyExpense(entry.getKey(), entry.getValue()))
                .sorted(Comparator.comparing(MonthlyExpense::getType))
                .collect(Collectors.toList());
    }

工作方式是对所有费用使用collect,按(groupBytype分组,并用作 summing 下游收集器。然后,使用此Map(类型和总金额之间)创建包含所需总费用的对象。下面的类是此Map的一个完整应用程序,供您使用:

import java.util.*;
import java.util.stream.Collectors;

public class FinancialCalculator {
    
    static class MonthlyExpense {
        private String type;
        private double amount;

        public MonthlyExpense(String type, double amount) {
            this.type = type;
            this.amount = amount;
        }
        
        public String getType() { return type; }
        public double getAmount() { return amount; }
        public String toString() { return String.format("%s: %.2f", type, amount); }
    }
    
    private static List<MonthlyExpense> createMonthlyExpenses(List<MonthlyExpense> expenses) {
        Map<String, Double> sums = expenses.stream()
                .collect(Collectors.groupingBy(
                            MonthlyExpense::getType, 
                            Collectors.summingDouble(MonthlyExpense::getAmount))
        );
        return sums.entrySet().stream()
                .map(entry -> new MonthlyExpense(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
    }
    
    public static void main(String[] args) {
        MonthlyExpense[] expenses = new MonthlyExpense[] {
                new MonthlyExpense("UTILITIES", 75),
                new MonthlyExpense("CREDIT", 1000),
                new MonthlyExpense("UTILITIES", 50),
                new MonthlyExpense("CREDIT", 2000),
                new MonthlyExpense("UTILITIES", 150),
                new MonthlyExpense("CAR", 344)
        };  
        System.out.println(createMonthlyExpenses(Arrays.asList(expenses)));
    }
}

Complete code on GitHub

相关问题