Iteração lista e somar todos os valores em que tipos são os mesmos

Angelina:

Eu preciso somar todos os valores na MonthlyExpenseslista onde os tipos são iguais.

No meu código eu estou anexando expensese obligationsa mesma lista de MonthlyExpenses.

Aqui está o meu código:

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

A 1st IF statement, se os retornos executados:

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
}

A 2nd IF statement, se os retornos executados:

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
}

Como faço o check-in List<MonthlyExpenses>se os tipos são iguais e resumir esses montantes e retornar essa nova lista?

Marco R .:

Você pode conseguir isso usando streamse collectors:

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

A forma como este trabalho é usando collectde todas as despesas agrupando-os por ( groupBy) seu typee usando como uma soma coletor downstream. Em seguida, use este mapa (entre tipos e quantidades totais) para criar os objetos com as despesas totais que você necessita. A classe a seguir é um aplicativo de trabalho cheio de isso em ação, para você jogar com:

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

código completo no GitHub

Espero que isto ajude.

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=202231&siteId=1
Recomendado
Clasificación