General answer - Such mapping is prohibited.
To map a list of objects to an object that would wrap this list could be done by:
/// your class with business code
List<Person> people = ....
new Group(people);
/// group class
public class Group {
private List<Person> people = new ArrayList<>();
public Group(List<Person> people) {
this.people = people
}
}
When the Group
would just have simply constructor with a list as param. You don't need to use Mapstruct for this.
In the mapstruct sources have this check Mapstruct github sources for MethodRetrievalProcessor.java:
Type parameterType = sourceParameters.get( 0 ).getType();
if ( parameterType.isIterableOrStreamType() && !resultType.isIterableOrStreamType() ) {
messager.printMessage( method, Message.RETRIEVAL_ITERABLE_TO_NON_ITERABLE );
return false;
}
So basically even Mapstruct team wants you to use mapping only when you need it. And doesn't want to allow transforming List<Object>
to another Object
as it doesn't make sense.
This would make some sense if you're adding some additional information(non-iterable :) ) for your Group
object, for example:
//group class
public class Group {
private Long someCounter;
private List<Person> people;
}
//mapper
@Mapping(target= "people", source ="people")
@Mapping(target= "someCounter", source ="counterValue")
Group toGroup(Long counterValue, List<Person> people);
But better use DTOs, Views, Entites and any other kind of objects that would hide all the nested stuff. In this case Mapstruct would be your greatest friend.