In this case is you can't use a PropertyMap
. If you want map it using ModelMapper
you must use a Converter
instead of PropertyMap
as you have done.
First your Converter would be as next where the source
is ComplexSource
and SimpleDTO
is the destination:
Converter<ComplexSource, SimpleDTO> converter = new AbstractConverter<ComplexSource, SimpleDTO>() {
@Override
protected SimpleDTO convert(ComplexSource source) {
SimpleDTO destination = new SimpleDTO();
List<String> sourceList = source.getElementList();
if(null != sourceList && !sourceList.isEmpty()){
int sizeList = sourceList.size();
destination.setFirstElement(sourceList.get(0));
destination.setLastElement(sourceList.get(sizeList - 1));
}
return destination;
}
};
Then you just need to add the converter to your ModelMapper
instance:
ModelMapper mapper = new ModelMapper();
mapper.addConverter(converter);
If you try the map, it works perfectly:
ComplexSource complexSource = new ComplexSource();
complexSource.setElementList(Arrays.asList("firstElement", "lastElement"));
SimpleDTO simpleDto = mapper.map(complexSource, SimpleDTO.class);
System.out.println(simpleDto);
Output
SimpleDTO [firstElement=firstElement, lastElement=lastElement]
Respect your comment, you need to check nulls if it is need in your source instance (in this case it is possible a null pointer if the list is null). But it inits for you the destination instance, even you can configure the destination instance how you want with a Provider
(Providers documentation).
In cases of special use cases like this, you need to worry about null checks and exceptions handling because a Converter
I would say is the way of modelmapper to map manually pojos.
The advantadges of use ModelMapper are explained in its web:
- If you configure it correctly in some cases it is no need to do the map manually.
- It centralizes the mapping.
- It provides a mapping API for handling special use cases. (This is your case)
- And so on (take a look its web)