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

Java 遍历列表并对类型相同的所有金额求和,java,algorithm,design-patterns,collections,java-8,Java,Algorithm,Design Patterns,Collections,Java 8,我需要将每月费用列表中类型相同的所有金额相加 在我的代码中,我将费用和义务添加到相同的月费用清单 这是我的密码: List<MonthlyExpenses> monthlyExpenses = new ArrayList<MonthlyExpenses>(); List<Expenses> expenses = getExpenses(borrower); List<Obligations> obligations = getObligation

我需要将
每月费用
列表中类型相同的所有金额相加

在我的代码中,我将
费用
义务
添加到相同的
月费用清单

这是我的密码:

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;
  }
}
如果执行
2nd IF语句
,则返回:

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
}
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
}

如果类型相同,如何签入
列表
,并将这些金额相加,然后返回新列表?

您可以使用
收集器来实现这一点:

    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());
    }


希望这能有所帮助。

您能分享一下您的BorrowerFinancialMonthlyExpenses类是什么样子吗?@marco-r我自动生成的BorrowerFinancialMonthlyExpenses类没有这两个元素的构造函数。i、 e:我不能这样做:.map(entry->newmonthlyexpense(entry.getKey(),entry.getValue()))。有没有其他方法让我映射我的“总和”?我是否可以创建BorrowerFinancialMonthlyExpenses borrowerFinancials=新的BorrowerFinancialMonthlyExpenses();在这里设置并返回?是的,你可以这样做。只需创建一个方法(
Expense createExpense(…)
),并替换条目的映射以使用此方法,而不是回答中使用的构造函数:
map(entry->createExpense(entry.getKey(),entry.getValue())
@marco-r在执行sums.entrySet().stream().map时,是否也可以按字母顺序对它们进行排序(条目->…?可以,只需在映射条目后添加我添加到答案中的额外行:
.sorted(Comparator.comparing(MonthlyExpense::getType))
我是这样做的:.sorted(Map.entry.comparingByKey())
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)));
    }
}