当前位置: 首页 > 知识库问答 >
问题:

MapStruct:将一个对象列表映射为两个字符串/UUID列表

曾骁
2023-03-14

我需要一个mapstruct映射,用于具有要以这种方式映射到目标类的对象列表的类:

//Source class:
public class VoucherTransaction {
    private List<Voucher> vouchers;
}

//TargetClass
public class VoucherTransactionServiceDTO {
    private List<UUID> voucherIds;
    private List<String> voucherSerials;
}

public class Voucher {
    private UUID id;
    private String serial;
}

共有1个答案

段晨
2023-03-14

在映射器类中,可以为每个目标使用表达式,并为目标中的每个列表实现单独的默认映射。

@Mapping(target = "voucherIds", expression = "java( mapVoucherListToVoucherIdList(transaction.getVouchers()) )")
@Mapping(target = "voucherSerials", expression = "java( mapVoucherListToVoucherSerialList(transaction.getVouchers()) )")
public VoucherTransactionServiceDTO TransactionToServiceDTO(VoucherTransaction transaction);

default List<UUID> mapVoucherListToVoucherIdList(List<Voucher> vouchers) {
    List<UUID> voucherIds = new ArrayList<>();
    if (vouchers != null && !vouchers.isEmpty())
        voucherIds = vouchers.stream().map(Voucher::getId).collect(Collectors.toList());
    return voucherIds;
}

default List<String> mapVoucherListToVoucherSerialList(List<Voucher> vouchers) {
    List<String> voucherSerials = new ArrayList<>();
    if (vouchers != null && !vouchers.isEmpty())
        voucherSerials = vouchers.stream().map(Voucher::getSerial).collect(Collectors.toList());
    return voucherSerials;
}
 类似资料: