Mapstruct:根据其中一个字段的值忽略集合的某些元素

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

我有这些豆子:

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...
}

我还有一些用于这些 bean 的 DTO

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...
}

(请注意 AddressDto class 缺少 deleted 字段)

我正在使用 Mapstruct 将这些 bean 映射到它们的 DTO。映射器是这样的:

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

现在,在映射中我想忽略 deleted 字段为 true 的地址实例。我有办法实现吗?

我不确定您是否可以从 MapStruct 功能中开箱即用。

来自文档:

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 - 为此,您需要自己实现映射此集合。

下面的例子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());
    }
}