Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
6.3k views
in Technique[技术] by (71.8m points)

java - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...