stream api笔记

986 阅读1分钟

1.分组求和

Map<CxFeeAmountType, BigDecimal> feeMap = feeBills.stream()
                .filter(receipt -> receipt.getWithtaxAmount() != null)
                .collect(Collectors.groupingBy(CxFeeAmountType::getType,
                        Collectors.reducing(BigDecimal.ZERO, CxFeeBillDTO::getWithtaxAmount, BigDecimal::add)));

因为会报空指针异常,所以最好先过滤掉为null的数据.

2.类型转换

source类:

public class CxReceiptDTO extends CxBaseDTO<CxReceiptDO> {

    public CxReceiptDTO() {
        super(new CxReceiptDO());
    }

    public CxReceiptDTO(CxReceiptDO entity) {
        super(entity);
    }

    public Integer getId() {
        return this.entity.getId();
    }

    public void setId(Integer id) {
        this.entity.setId(id);
    }

    ...
}

目标类:

@Data
public class CxReceiptEVO extends CxBaseEVO<CxReceiptDTO> {

    public CxReceiptEVO(CxReceiptDTO dto) {
        super(dto);
    }

    @ExcelIdentifier(name="主键", orderNum = 1)
    public Integer getId() {
        return this.dto.getId();
    }

    @ExcelIdentifier(name="收货单号", orderNum = 2)
    public String getReceiptNo() {
        return this.dto.getReceiptNo();
    }

    ...
}

转换代码:

receipts.stream().map(CxReceiptEVO::new).collect(Collectors.toList())