ModelMapper库是否支持ArrayList或HashSet等集合?

Ray*_*Ray 28 java modelmapper

此问题与AutoMapper无关.我的问题是关于java中的ModelMapper,但是我无法为modelmapper创建新的标签作为我的小声誉.抱歉混淆.

无论如何,我的问题是modelmapper库是否支持arraylist或hashset等集合?它似乎不支持集合映射的集合.这是真的吗?

Jos*_*osé 55

您还可以直接映射collections():

    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);
Run Code Online (Sandbox Code Playgroud)

有关映射泛型的文档.


Pho*_*Bui 8

或者使用 Java 8:

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

  • 这样做的缺点是 modelMapper 没有完成从一个列表到另一个列表的所有映射。通过使用 TypeToken,从一个列表到另一个列表的映射全部封装在 modelMapper 中。 (2认同)

Ced*_*ont 5

如果你使用数组,你也可以避免 TypeToken 的东西:

  List<PropertyDefinition<?>> list = ngbaFactory.convertStandardDefinitions(props);
  ModelMapper modelMapper = new ModelMapper();
  PropertyDefinitionDto[] asArray = modelMapper.map(list, PropertyDefinitionDto[].class);
Run Code Online (Sandbox Code Playgroud)


Jon*_*han 4

是 - 支持集合到集合映射。前任:

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"));
}
Run Code Online (Sandbox Code Playgroud)