Group by two fields then summing BigDecimal

后端 未结 3 972
轮回少年
轮回少年 2021-02-04 11:19

I have a list of taxes:

TaxLine = title:\"New York Tax\", rate:0.20, price:20.00
TaxLine = title:\"New York Tax\", rate:0.20, price:20.00
TaxLine = title:\"Count         


        
3条回答
  •  终归单人心
    2021-02-04 12:08

    Unable to sum up the grouped field can be achieved by Defining a new class called TitleRate inside Taxline class as below.

        class Taxline{
            public static class TitleRate {
                public TitleRate(String title, int taxline) {
                    ...
                }
    
            }
    
            public TitleRate getTitleRate() {
                return new TitleRate(title, taxline);
            }
        }
    

    To sum the price by grouping title and taxrate, below can be used.

    Map> groupedData = people.collect(Collectors.groupingBy(Taxline::getTitleRate));
    
      List groupedTaxLines = new ArrayList();
      BigDecimal groupedRate = BigDecimal.ZERO;
      for (Map> entry : groupedData.entrySet())
      {
        for(Taxline taxline : entry.getValue()){
            groupedRate = groupedRate.add(taxline.getPrice());
        }
        groupedTaxLines.add(new Taxline(entry.getKey().getTitle, entry.getKey().getRate(), groupedRate));
            groupedRate = BigDecimal.ZERO;
       }
    

提交回复
热议问题