我正在尝试使用mapstruct将不可迭代的值(即字符串)映射到字符串列表。
所以我正在使用

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


这里abcList<String>

xyzString

但是为此,我需要明确检查null

通过将不可迭代转换为可迭代,是否有更好的方法将不可迭代映射为可迭代。

最佳答案

这是不可迭代的示例:

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

    }

}

09-26 17:22