public class SimpleDTO{
private String firstElement;
private String lastElement;
}
public class ComplexSource{
private List<String> elementList;
}
I tried to map it usingmap().setFirstElement(source.getElementList().get(0)) but I get an error stating "1) Invalid source method java.util.List.get(). Ensure that method has zero parameters and does not return void."
How do I map an element in a list to a field in a Pojo using ModelMapper or any other alternative?
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With