【问题标题】:Is it possible to convert from HashMap to List using MapStruct是否可以使用 MapStruct 从 HashMap 转换为 List
【发布时间】:2021-02-06 10:09:11
【问题描述】:

我知道有一个类似的问题(请参阅question),但我没有找到有用的答案。假设我有以下课程:

class QuestionType {
    private String type;
}

class Profile {
    private String name;
    private int id;
}

class ProfileResponse {
    private String name;
    private int id;
    private String type;
}

如何使用 MapStruct (1.3.1) 将 HashMap<QuestionType, Profile> 转换为 List<ProfileResponse>

@Mapper(componentModel = "spring")
public interface ProfileResponseMapper {
    List<ProfileResponse> toProfileResponse(Map<QuestionType, Profile> profiles);
}

【问题讨论】:

    标签: java list dictionary mapping mapstruct


    【解决方案1】:

    MapStruct 没有将Map 映射到List 的隐式转换机制。但是,您可以使用技巧将 Map 理解为 Entry 的集合,并将每个条目映射到列表项:

    @Mapper(componentModel = "spring")
    public interface ProfileResponseMapper {
    
        @Mapping(target = "type", source = "key.type")
        @Mapping(target = "name", source = "value.name")
        @Mapping(target = "id", source = "value.id")
        ProfileResponse map(Map.Entry<QuestionType, Profile> profile);
            
        default List<ProfileResponse> toProfileResponse(Map<QuestionType, Profile> map) {
            return map.entrySet()
                      .stream()
                      .map(this::map)
                      .collect(Collectors.toList());
        }
    }
    
    ProfileResponseMapper mapper = ...    // ProfileResponseMapper.INSTANCE or @Autowired 
    Map<QuestionType, Profile> map = ...  // input Map
    
    List<ProfileResponse> profileResponseList = mapper.toProfileResponse(map);
    

    代码利用 Java 8 default 方法和 Stream API 的优势,否则使用 abstract class 和 for-each 循环。

    【讨论】:

    • 即使使用 Java 11 我也会这样做(我实际上是在使用 Java 11 尝试这个示例,但 default 和 Stream API 功能来自 Java 8)。如果您对我的解决方案有任何问题,请具体说明,到目前为止,该代码对我有效。
    【解决方案2】:

    我更愿意遵循 KISS 原则: 通过地图的双向消费者迭代,创建您的 ProfileResponse 对象并将它们放入列表中。

    map.forEach (key, val -> 
        {
            ProfileRespone respone = new ProfileResponse(key.type, val.name, val.id);
            list.add(response);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多