Java 8 stream - merge collections of objects sharing the same Id

后端 未结 6 1683
后悔当初
后悔当初 2021-02-13 15:11

I have a collection of invoices :

class Invoice {
  int month;
  BigDecimal amount
}

I\'d like to merge these invoices, so I get one invoice pe

6条回答
  •  暖寄归人
    2021-02-13 15:51

    I think if your application do not support lambda than this might be a suitable answer eg (Android minSdkVersion=16 do not support lambda)

    public static List mergeAmount(List invoiceList) {
     List newInvoiceList = new ArrayList<>();
      for(Invoice inv: invoiceList) {
        boolean isThere = false;
         for (Invoice inv1: newInvoiceList) {
          if (inv1.getAmount() == inv.getAmount()) {
             inv1.setAmount(inv1.getAmoount()+inv.getAmount());
             isThere = true;
             break;
           }             
         }
        if (!isThere) {
            newInvoiceList.add(inv);
        } 
     }
      return newInvoiceList;
    }
    

提交回复
热议问题