Search code examples
javaspring-bootgroup-byhashmapsum

How to group the elements of a HashMap by key and sum the values?


Illustrative image of what I currently have in the HashMap.

Hello, I would like to please group the HashMap items by nature and then sum the amounts for the repeating items. I have to save the HashMap elements in the PartDonNature model.

public class PartNatureDon extends BaseEntity{

    @ManyToOne
    @JoinColumn(name = "nature_don_col_id", nullable = false)
    private NatureDon natureDon;

    @ManyToOne
    @JoinColumn(name = "assistance_col_id", nullable = false)
    private Assistance assistance;

    @Column
    private double montant;
}
public void savePartNatureDon(){
    PartNatureDon partNatureDon = new PartNatureDon();
    Set<Don> dons = selected.getDons();

    List<NatureDon> natureDonList = new ArrayList<>();
    for (Don don : dons){
        partNatureDon.setAssistance(don.getAssistance());
        
        List<NatureDon> natureDons = don.getNatureDonList();
        HashMap<String, Double> montant = new HashMap<>();
        for (NatureDon natureDon : natureDons){

            if (!natureDonList.stream().anyMatch(n->n.getLibelle().equals(natureDon.getLibelle()))) {
                natureDonList.add(natureDon);

                natureDonList.forEach (natureDon1 -> {
                        montant.putIfAbsent(natureDon1.getLibelle(), Double.valueOf(don.getMontantNatureDon().get(natureDon1.getLibelle())));
                        montant.computeIfPresent(natureDon1.getLibelle(), (n, nature) -> Double.valueOf(nature + don.getMontantNatureDon().get(natureDon1.getLibelle())));
                });
            }

        }

    }
}

Solution

  • natureDonList.forEach (natureDon1 -> {
    if(montant.containtsKey(natureDon1.getLibelle())){
       montant.put(natureDon1.getLibelle(), montant.get(natureDon1.getLibelle())+Double.valueOf(don.getMontantNatureDon().get(natureDon1.getLibelle())));
    }else{
     montant.putIfAbsent(natureDon1.getLibelle(), Double.valueOf(don.getMontantNatureDon().get(natureDon1.getLibelle())));
    }
    
                });