Home > Back-end >  MapStruct List<String> to Single Object with Nested List of Objects
MapStruct List<String> to Single Object with Nested List of Objects

Time:01-11

I'm trying to convert a List<String> to the below DomainUpdate object. The DomainUpdate object contains a List of Domains and a Domain just have a String value.

DomainUpdate{
    List<Domain> domains;
}

Domain{
    String value;
}

I can't seem to find any good documentation on how to do this and my current implementation just complains: error: Can't generate mapping method from iterable type from java stdlib to non-iterable type.

Mapper

@Mapper(componentModel = "spring", collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface DomainProtobufMapper {
    DomainUpdate domainsToProtobuf(List<String> domains);

}

CodePudding user response:

You can't directly match this but let's create your custom method with the return type you want and the argument you need to convert.

@Mapper
public interface MyMapper {

    default DomainUpdate domainsToProtobuf(List<String> values) {
        DomainUpdate domainUpdate = new DomainUpdate();
        domainUpdate.setDomains(valueToDomain(values));
        return domainUpdate;
    }

    Domain valueToDomain(String value);
    List<Domain> valueToDomain(List<String> values);
}

OR

You can do it with a dummy parameter like in this article.

@Mapper
public interface MyMapper {

    default DomainUpdate domainsToProtobuf(List<String> values) {
        return domainsToProtobuf(null, values);
    }

    @Mapping(target = "domains", source = "values")
    DomainUpdate domainsToProtobuf(Integer dummy, List<String> values);

    Domain valueToDomain(String value);
    List<Domain> valueToDomain(List<String> values);
}
  • Related