How to convert nested Map to List of POJO using Mapstruct

Viewed 128

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;
2 Answers

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


}

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

Related