MapStruct String to List mapping

suresh picture suresh · May 10, 2016 · Viewed 17.7k times · Source

How would i map String to List and List to String?

Consider we have following classess

class People{
    private String primaryEmailAddress;
    private String secondaryEmailAddress;
    private List<String> phones;
    //getter and setters
}

class PeopleTO{
    private List<String> emailAddress;
    private String primaryPhone;
    private String secondaryPhone;
    //getter and setters
}

In Dozer and Orika, we can easily map with the following line of code

fields("primaryEmailAddress", "emailAddress[0]")
fields("secondaryEmailAddress", "emailAddress[1]")

fields("phones[0]", "primaryPhone")
fields("phones[1]", "secondaryPhone")

How i can do the same kind of mapping in MapStruct? Where would i find more examples on mapstruct?

Answer

lpacheco picture lpacheco · Apr 8, 2017

The example below maps elements from the emailAddress list in PeopleTO into the primaryEmailAddress and secondaryEmailAddress properties of People.

MapStruct can't directly map into collections, but it allows you to implement methods that run after a mapping to complete the process. I've used one such method for mapping the primaryPhone and secondaryPhone properties of PeopleTO into elements of the phones list in People.

abstract class Mapper {
    @Mappings({
        @Mapping(target="primaryEmailAddress", expression="emailAddress != null && emailAdress.size() >= 1 ? emailAdresses.get(0) : null"),
        @Mapping(target="secondaryEmailAddress", expression="emailAddress != null && emailAdress.size() >= 2 ? emailAdresses.get(1) : null"),
        @Mapping(target="phones", ignore=true)
    })
    protected abstract People getPeople(PeopleTO to);

    @AfterMapping
    protected void setPhones(PeopleTO to, @MappingTarget People people) {
        people.setPhones(new List<String>());
        people.getPhones().add(to.primaryPhone);
        people.getPhones().add(to.secondaryPhone);
    }
}