如何将对象列表设置为另一个对象列表



场景我有两个同名的DTO类(CobrandedCardDto),它们具有相同的属性,但在不同的包中。

包装为:

1. com.loyalty.marketplace.offers.member.management.outbound.dto
2. com.loyalty.marketplace.outbound.dto

CobrandedCardDto中的属性为:

private String partnerCode;
private String bankId;
private String status;
private String cardType;

我有来自包(com.loyalty.marketplace.outbound)中的服务的List<CobrandedCardDto>,我需要在包(com.loyalty.marketplace.offers.member.management.outbound)中将其设置为List<CobrandedCardDto>

基本上我想做这样的事情;

memberDetails.setCobrandedCardDetails(MemberAccountInfoDto.getCobrandedCardDetails());

其中cobrandedCardDetailsList<CobrandedCardDto>的变量

问题我无法设置列表。我正面临这个错误。我该如何解决这个问题?

方法setCobrandedCardDetails(java.util.List<com.忠诚度.markety.offers.member.management.outbound.dto.CobrandedCardDto>)类型中的GetMemberResponse不适用于参数(java.util.List<com.delity.markety.outbound.dto.CobrandedCardDto>)

您需要从一种类型映射到另一种类型。一个简单的解决方案是手动流式传输它们并映射,如下所示:

List<com.loyalty.marketplace.outbound.dto.CobrandedCardDto> dtos = ...;
List<com.loyalty.marketplace.offers.member.management.outbound.CobrandedCardDto> mappedDtos = dtos.stream()
.map(dto -> new com.loyalty.marketplace.offers.member.management.outbound.CobrandedCardDto(
dto.getPartnerCode(),
dto.getBankId(),
dto.getStatus(),
dto.getCardType()
))
.toList();

如果也要对其他对象执行此操作,则可以考虑使用映射库,如mapstruct:https://www.baeldung.com/mapstruct

附言:考虑重命名其中一个,这样你就不需要完全限定的名称了。

更新:如果你不想添加@AllArgsConstructor,你可以看到setters:

.map(dto -> {
var mappedDto = new com.loyalty.marketplace.offers.member.management.outbound.CobrandedCardDto();
mappedDto.setPartnerCode(dto.getPartnerCode());
mappedDto.setBankId(dto.getBankId());
mappedDto.setStatus(dto.getStatus());
mappedDto.setCardType(dto.getCardType());    
return mappedDto;
}).toList(); 

不过,在我看来,全args构造函数解决方案看起来更好。

由于此方法是一种应跨不同类使用的Mapper方法,因此有必要将其作为Mapper类中的静态Mapper方法。

假设您有以下Mapper类:

CobrandedCardMapper

public static List<com.loyalty.marketplace.offers.member.management.outbound.CobrandedCardMapper> getMappedListOfCobrandedCard(List<CobrandedCardMapper> list){
return list.stream()
.map(cobrandedCardMapper ->{
com.loyalty.marketplace.offers.member.management.outbound.CobrandedCardMapper cobrandedCardMapperDTO = new com.loyalty.marketplace.offers.member.management.outbound.CobrandedCardMapper();
//Then use Apache Commons  Bean Utils copy properties function based on field name
BeanUtils.copyProperty(cobrandedCardMapperDTO,cobrandedCardMapper);
return cobrandedCardMapperDTO;
).collect(Collectors.toList());
}

然后您可以调用集合中的方法,以获得转换后的列表

最新更新