I am trying to use ModelMapper
to map
a collection
of sub-objects to a list
of id numbers.
public class Child {
private int id;
private String childName;
}
public class Parent {
private Set<Child> children;
private String parentName;
}
public class ParentDto {
private int[] children; // Or use ArrayList<Integer>
private String parentName;
}
How do I tell ModelMapper
to flatten the set of Child objects to an array of id numbers?
My first attempt is this but does not seem correct:
modelMapper.addMappings(new PropertyMap<Parent, ParentDto>() {
@Override
protected void configure() {
using(ctx -> ctx.getSource().stream().map(Parent::getId).collect(Collectors.toList())
.map().setChildren(source.getId()));
};
});
Type listType = new TypeToken<ArrayList<ParentDto>>() {}.getType();
ArrayList<ParentDto> parentDtos = new ArrayList<>();
parentDtos = modelMapper.map(parents, listType);
The setChildren
call seems like it needs to be map().add()
but that does not work either.
Ideas are welcome.