5

I want to have a 2 way mapping from a List of an object to an Object which contains a List.

class Person {
  String firstName;
  String lastName;
}

class Group { // Source
  List<Person> people;
  String groupID; 
  ...
}

class Employee { // target
  String firstName;
  String lastName;
  String employeeNumber;
  ...
}

I used ReportingPolicy.IGNORED to ignore all the irrelevant fields. I just want a mapping between Group to List with the fields firstName and lastName.

Is it possible at all? I have tried but it's giving me error during build "impossible to map iterable to non-iterable."

@Mapping(target="people", source".")
Group map(List<Employee>)

2 Answers 2

6

Mapstruct does not support such kind mapping. See Mapstruct contributor answer regarding this problem.
Like workaround you can implement your own mapping method for converting to wrapped class.

@org.mapstruct.Mapper
public interface Mapper {
    List<Person> map(List<Employee> employees);

    Person map(Employee employee);

    default Group mapGroup(List<Employee> employees) {
        Group group = new Group();
        group.people = map(employees);
        return group;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

MapStruct supports mapping from a source parameter to a target parameter. This means that you can configure MapStruct to map the source list parameter to a target list property. However, as pointed out in https://stackoverflow.com/a/71181377/1115491 it is not possible to map form a single collection parameter to a target parameter. The only way it works is if there are multiple source parameters.

e.g.

@Mapper
public interface Mapper {

    @Mapping(target = "people", source = "employees")
    @Mapping(target = "groupID", source = "groupId")
    Group map(String groupId, List<Employee> employees);

}

4 Comments

It is not working in 1.5.0.Beta2. I checked this case.
You are right, @Eugene. I was thinking about another use case we used to have. It is working correctly if there are 2 source parameters. I'll update the answer
This is exactly what I was trying to do. Mapping from an iterable to another iterable inside of an object (and vice versa). But I always get a compilation error "Can't generate mapping method from non-iterable type to iterable type". No matter how I change the source/target.
The updated answer is working well. I have just tested it. I will undo the decrease point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.