开发者

Does ModelMapper library support collections like ArrayList or HashSet?

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?


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.


Or with Java 8:

List<Target> targetList =
    sourceList
        .stream()
        .map(source -> modelMapper.map(source, Target.class))
        .collect(Collectors.toList());


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);


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"));
}


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜