Reputation: 201
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?
Upvotes: 2
Views: 2485
Reputation: 310
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());
}
}
Upvotes: 6