Home > Back-end >  Map collection to an object using mapstruct
Map collection to an object using mapstruct

Time:10-22

How can I define following mapping using Mapstruct java bean mapping. The problem how do I map the List ( with just one element) in source class to TargetPhone class

Source classes

class Source{
    private String name;
    private int age;
    **This list always contain one element   
    and I cannot change this behavior or structure of this class**
    private List<Phone> phones;
}


class Phone{
    private Long id;
    private String phoneNumber;
    private String phoneColor;
    // getters and setters
}

Target classes

class Target{
    private String myName; **-->should map to Source.name**
    private int myAge; **-->should map to Source.age**
    private TargetPhone targetPhone;
    // getters and setters
}


class TargetPhone{
        private Long myId;  **-->should map to Source.phones[0].id**
        private String myPhoneNumber;  **-->should map to Source.phones[0].phoneNumber**
        private String myPhoneColor;  **-->should map to Source.phones[0].phoneColor**
        // getters and setters
    }

CodePudding user response:

Your mapper should be defined as shown below.

@Mapper
public interface MyMapper {

    @Mapping(source="name", target="myName")
    @Mapping(source="age", target="myAge")
    @Mapping(source="phones", target="targetPhone")
    Target sourceToTarget(Source source);


    @Mapping(source = "id", target = "myId")
    @Mapping(source = "phoneNumber", target = "myPhoneNumber")
    @Mapping(source="phoneColor", target="myPhoneColor")
    TargetPhone phoneToTargetPhone(Phone phone);

    default TargetPhone listPhonesToTargetPhone(List<Phone> phones){
        return phoneToTargetPhone(phones.get(0));
    }

}

Where the default method does the magic of mapping the first element of Phone list to TargetPhone.

  • Related