31

This question is not relating with AutoMapper. My question is about ModelMapper in java, however I cannot create new tag for modelmapper as my little reputation. Sorry for confusion.

Anyway, my question is that does modelmapper library support collections like arraylist or hashset? it seems not support collection to collection mapping. Is it true?

Jimmy Bogard
  • 26,045
  • 5
  • 74
  • 69
Ray
  • 4,038
  • 8
  • 36
  • 48

5 Answers5

63

You can also map collections () directly:

    List<Person> persons = getPersons();
    // Define the target type
    java.lang.reflect.Type targetListType = new TypeToken<List<PersonDTO>>() {}.getType();
    List<PersonDTO> personDTOs = mapper.map(persons, targetListType);

Documentation on mapping Generics.

real_paul
  • 574
  • 2
  • 22
José
  • 3,112
  • 1
  • 29
  • 42
8

Or with Java 8:

List<Target> targetList =
    sourceList
        .stream()
        .map(source -> modelMapper.map(source, Target.class))
        .collect(Collectors.toList());
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
Phong Bui
  • 441
  • 3
  • 7
5

You can also avoid the TypeToken stuff if you work with arrays:

  List<PropertyDefinition<?>> list = ngbaFactory.convertStandardDefinitions(props);
  ModelMapper modelMapper = new ModelMapper();
  PropertyDefinitionDto[] asArray = modelMapper.map(list, PropertyDefinitionDto[].class);
Cedric Dumont
  • 1,009
  • 17
  • 38
4

Yes - Collection to Collection mapping is supported. Ex:

static class SList {
    List<Integer> name;
}

static class DList {
    List<String> name;
}

public void shouldMapListToListOfDifferentTypes() {
    SList list = new SList();
    list.name = Arrays.asList(Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3));
    DList d = modelMapper.map(list, DList.class);

    assertEquals(d.name, Arrays.asList("1", "2", "3"));
}
Jonathan
  • 5,027
  • 39
  • 48
1

Even if all the answers are correct in their own way, I would like to share a rather simplified and easy way of doing it. For this example let's supose we have a list of entities from the database and we want to map into his respective DTO.

Collection<YourEntity> ListEntities = //GET LIST SOMEHOW;
Collection<YourDTO> ListDTO = Arrays.asList(modelMapper.map(ListEntities, YourDTO[].class));

You can read more at: https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html

You can still use a more old school way to do it: https://www.baeldung.com/java-modelmapper-lists

Use with moderation (or not).

William
  • 33
  • 6
  • The resultant List will be sorted in what way? Since the target class is provided as an array (YourDTO[]) then converted to a List. Is there a way of knowing how the resultant list will be sorted? – Lewis Munene May 27 '21 at 15:46
  • @LewisMunene ListDTO should keep the same order as the ListEntities. https://stackoverflow.com/questions/4972406/does-the-list-returned-from-arrays-aslist-maintain-the-same-order-as-the-origina – William May 28 '21 at 12:15