如何使用 Mapstruct 将嵌套 Map 转换为 POJO 列表

发布于 2025-01-13 07:20:28 字数 291 浏览 2 评论 0 原文

如何转换 Map>使用 MapStruct 列出?

source:
Map<String, Map<String, Long>>

target:
List<DTO1>


DTO1:
private String name;
private List<DTO2> dto2List;

DTO2:
private String type;
private Long count;

How to convert Map<String, Map<String, Long>> to List using MapStruct?

source:
Map<String, Map<String, Long>>

target:
List<DTO1>


DTO1:
private String name;
private List<DTO2> dto2List;

DTO2:
private String type;
private Long count;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等风也等你 2025-01-20 07:20:28

可以使用一些自定义方法来进行此类映射。我假设映射条目集需要映射到列表。

例如

@Mapper
public abstract class MyMapper {


    public List<DTO1> map(Map<String, Map<String, Long>> source) {
        if ( source == null ) {
            return null;
        }

        return toDto1List( source.entrySet() );
    }

    protected abstract List<DTO1> toDto1List(Collection<Map.Entry<String, Map<String, Long>>> collection);
    protected abstract List<DTO2> toDto2List(Collection<Map.Entry<String, Long>> collection);

    protected DTO1 entryToDto1(Map.Entry<String, Map<String, Long>> entry) {
        if ( entry == null ) {
            return null;
        }

        return new DTO1( entry.getKey(), toDto2List( entry.getValue().entrySet() ) );
    }

    protected DTO2 entryToDto2(Map.Entry<String, Long> entry) {
        if ( entry == null ) {
            return null;
        }

        return new DTO2( entry.getKey(), entry.getValue() );
    }


}

Doing such a mapping is possible with some custom methods. I assume that the map entry set needs to be mapped to the list.

e.g.

@Mapper
public abstract class MyMapper {


    public List<DTO1> map(Map<String, Map<String, Long>> source) {
        if ( source == null ) {
            return null;
        }

        return toDto1List( source.entrySet() );
    }

    protected abstract List<DTO1> toDto1List(Collection<Map.Entry<String, Map<String, Long>>> collection);
    protected abstract List<DTO2> toDto2List(Collection<Map.Entry<String, Long>> collection);

    protected DTO1 entryToDto1(Map.Entry<String, Map<String, Long>> entry) {
        if ( entry == null ) {
            return null;
        }

        return new DTO1( entry.getKey(), toDto2List( entry.getValue().entrySet() ) );
    }

    protected DTO2 entryToDto2(Map.Entry<String, Long> entry) {
        if ( entry == null ) {
            return null;
        }

        return new DTO2( entry.getKey(), entry.getValue() );
    }


}
孤独患者 2025-01-20 07:20:28

map.entrySet().stream().map(entry -> new DTO1(...)).collect(Collectors.toList())

map.entrySet().stream().map(entry -> new DTO1(...)).collect(Collectors.toList())

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文