Forece85
Forece85

Reputation: 518

How to convert nested Map to List of POJO using Mapstruct

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;

Upvotes: 2

Views: 352

Answers (2)

Filip
Filip

Reputation: 21461

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


}

Upvotes: 1

Reinhold
Reinhold

Reputation: 584

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

Upvotes: 0

Related Questions