简体   繁体   中英

Mapstruct: Ignore some elements of a collection based on the value of one of their fields

I have these beans:

public class Company {
    private String name;
    private List<Address> addresses;
    ...some other fields...
}

public class Address {
    private String street;
    private String city;
    private boolean deleted;
    ...some other fields...
}

I also have some DTOs for those beans

public class CompanyDto {
    private String name;
    private List<AddressDto> addresses;
    ...some other fields...
}

public class AddressDto {
    private String street;
    private String city;
    ...some other fields...
}

(Please note that the AddressDto class lacks the deleted field)

I'm using Mapstruct to map those beans to their DTOs. The mapper is this:

@Mapper
public interface CompanyMapper {
    CompanyDto companyToCompanyDto(Company company);
    List<AddressDto> ListAddressToListAddressDto(List<Address> addresses);
}

Now, in the mapping I want to ignore the Address instances whose deleted field is true . Is there a way for me to achieve that?

I'm not sure if you can get it out of the box from MapStruct features.

From Documentation:

The generated code will contain a loop which iterates over the source collection, converts each element and puts it into the target collection. - https://mapstruct.org/documentation/stable/reference/html/#mapping-collections

I want to ignore the Address instances whose deleted field is true - to do it you need your own implementation of mapping this collection.

Below an example of CompanyMapper

@Mapper
public interface CompanyMapper {
    CompanyDto companyToCompanyDto(Company company);
    AddressDto addressToAddressDto(Address address);

    default List<AddressDto> addressListToAddressDtoList(List<Address> list) {
        return list.stream()
                   .filter(address -> !address.isDeleted())
                   .map(this::addressToAddressDto)
                   .collect(Collectors.toList());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM