1. 程式人生 > >Java 物件按照多個屬性來合併。

Java 物件按照多個屬性來合併。

private static final String detailId="detailId";
private static final String shelfBinCode="shelfBinCode";
/**
 * 相同商品+相同貨架相同貨位合併
 * @param
 * @return
 */
public  List<ReceiptBackDetailSub> mergeSub(List<ReceiptBackDetailSub>  subs){
    HashMap<String,ReceiptBackDetailSub> receiptNoteDetailSub=new HashMap<>();

    if(CollectionUtil.isNotEmpty(subs)){
        for(ReceiptBackDetailSub sub:subs){
            String key=genKeySub(sub);
            ReceiptBackDetailSub existSub=receiptNoteDetailSub.get(key);
            if(existSub  == null){
                receiptNoteDetailSub.put(key,sub);
            }else{

                existSub.setReceiptAmount(existSub.getReceiptAmount()+sub.getReceiptAmount());
                existSub.setPackageAmount(existSub.getPackageAmount()+sub.getPackageAmount());
                flag=true;
            }
        }
    }
    List<ReceiptBackDetailSub> results= Arrays.asList(receiptNoteDetailSub.values().toArray(new ReceiptBackDetailSub[0]));
    return results;
}

/**

按照需要的屬性來拼裝一個字串。

*/

public static String genKeySub(ReceiptBackDetailSub sub){
    StringBuilder keyBuilder=new StringBuilder();

    if(StringUtils.isNotEmpty(sub.getShelfBinCode())){
        keyBuilder.append(shelfBinCode).append(sub.getShelfBinCode());
    }
    if(sub.getReceiptBackDetailId()!=null){
        keyBuilder.append(detailId).append(sub.getReceiptBackDetailId());
    }
    return   keyBuilder.toString();
}