13

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?

2 Answers 2

19

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);
    }
}
0
3

I could see some examples here: https://github.com/mapstruct/mapstruct-examples

Checkout this module for your specific requirement (Iterable to non-Iterable): https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-iterable-to-non-iterable

and another one here: http://blog.goyello.com/2015/09/08/dont-get-lost-take-the-map-dto-survival-code/

Not sure if it is possible to map the non-iterable to Iterable.

1
  • It's worked for one string to list mapping but i want to map primary and secondary email address to list of email address when i do that it throws same field cannot be mapped
    – suresh
    May 11, 2016 at 10:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.