Search code examples
javamapstruct

mapping of non-iterable to iterable in mapstruct


I am trying to map a non-iterable value i.e. String to a list of string using mapstruct. So I am using

@Mapping(target = "abc", expression = "java(java.util.Arrays.asList(x.getY().getXyz()))")

Here abc is List<String>

xyz is a String

But for this i need to check for null explicitly.

Is there any better way of maaping a non-iterable to iterable by converting non iterable to iterable.


Solution

  • Here is an example for non iterable-to-iterable:

    public class Source {
    
        private String myString;
    
        public String getMyString() {
            return myString;
        }
    
        public void setMyString(String myString) {
            this.myString = myString;
        }
    
    }
    
    public class Target {
    
        private List<String> myStrings;
    
        public List<String> getMyStrings() {
            return myStrings;
        }
    
        public void setMyStrings(List<String> myStrings) {
            this.myStrings = myStrings;
        }   
    
    }
    
    @Qualifier
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public @interface FirstElement {
    }
    
    public class NonIterableToIterableUtils {
    
         @FirstElement
            public List<String> first(String in ) {
                if (StringUtils.isNotEmpty(in)) {
                    return Arrays.asList(in);
    
                } else {
                    return null;
                }
            }
    
    }
    
    @Mapper( uses = NonIterableToIterableUtils.class )
    public interface SourceTargetMapper {
    
        SourceTargetMapper MAPPER = Mappers.getMapper( SourceTargetMapper.class );
    
        @Mappings( {
            @Mapping( source = "myString", target = "myStrings", qualifiedBy = FirstElement.class )
        } )
        Target toTarget( Source s );
    }
    
    public class Main {
    
        public static void main(String[] args) {
            Source s = new Source();
            s.setMyString("Item");
    
            Target t = SourceTargetMapper.MAPPER.toTarget( s );
            System.out.println( t.getMyStrings().get(0));
    
        }
    
    }