Java ModelMapper库是否支持ArrayList或HashSet之类的集合?

Java ModelMapper库是否支持ArrayList或HashSet之类的集合?,java,modelmapper,Java,Modelmapper,这个问题与AutoMapper无关。 我的问题是关于java中的ModelMapper,但是我不能为ModelMapper创建新标记,因为我的名声不好。抱歉搞混了 无论如何,我的问题是,库是否支持arraylist或hashset之类的集合?它似乎不支持集合到集合的映射。 是吗?是-支持集合到集合的映射。例: static class SList { List<Integer> name; } static class DList { List<String&

这个问题与AutoMapper无关。 我的问题是关于java中的ModelMapper,但是我不能为ModelMapper创建新标记,因为我的名声不好。抱歉搞混了

无论如何,我的问题是,库是否支持arraylist或hashset之类的集合?它似乎不支持集合到集合的映射。
是吗?

是-支持集合到集合的映射。例:

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"));
}
静态类SList{
名单名称;
}
静态类数据列表{
名单名称;
}
public void应映射列表到不同类型的列表(){
SList list=新SList();
list.name=Arrays.asList(Integer.valueOf(1)、Integer.valueOf(2)、Integer.valueOf(3));
DList d=modelMapper.map(列表,DList.class);
资产质量(d.名称、数组、asList(“1”、“2”、“3”);
}

您也可以直接映射集合():

List persons=getPersons();
//定义目标类型
java.lang.reflect.Type targetListType=new-TypeToken(){}.getType();
List personDTOs=mapper.map(persons,targetListType);

.

如果使用数组,也可以避免使用TypeToken:

  List<PropertyDefinition<?>> list = ngbaFactory.convertStandardDefinitions(props);
  ModelMapper modelMapper = new ModelMapper();
  PropertyDefinitionDto[] asArray = modelMapper.map(list, PropertyDefinitionDto[].class);
List或使用Java 8:

List<Target> targetList =
    sourceList
        .stream()
        .map(source -> modelMapper.map(source, Target.class))
        .collect(Collectors.toList());
列出目标列表=
源列表
.stream()
.map(source->modelMapper.map(source,Target.class))
.collect(Collectors.toList());

即使所有答案都是正确的,我还是想分享一种简单易行的方法。在本例中,我们假设数据库中有一个实体列表,我们希望映射到其各自的DTO中

Collection<YourEntity> ListEntities = //GET LIST SOMEHOW;
Collection<YourDTO> ListDTO = Arrays.asList(modelMapper.map(ListEntities, YourDTO[].class));
Collection listenties=//以某种方式获取列表;
Collection ListDTO=Arrays.asList(modelMapper.map(listenties,YourDTO[].class));
您可以在以下网址阅读更多内容:

您仍然可以使用更老派的方式来完成:


与适度(或不适度)一起使用。

在本例中,您在集合周围使用了两个包装器类。没有它们可能吗?@miguelcobain-是的,包装器恰好就是我给出的例子。这样做的缺点是modelMapper没有完成从一个列表到另一个列表的所有映射。通过使用TypeToken,从一个列表到另一个列表的映射都封装在modelMapper中。我认为这种方式更具可读性,我只是讨厌“{}.getType()”(如果重新格式化代码,它看起来会很难看)。我说“或者…”不过:我喜欢这个解决方案!优雅的解决方案Grande bro,这对我很有用。结果列表将以什么方式排序?因为目标类是作为数组(YourDTO[])提供的,然后转换为列表。有没有办法知道结果列表将如何排序?@lewismunelistdto应该保持与列表项相同的顺序。
Collection<YourEntity> ListEntities = //GET LIST SOMEHOW;
Collection<YourDTO> ListDTO = Arrays.asList(modelMapper.map(ListEntities, YourDTO[].class));