简体   繁体   English

将列表映射到 Dozer 中的列表

[英]Mapping list to list in Dozer

List<CustomerData> mapAddress(List<Address> addressList){

   List<Customer> customerData = new ArrayList<Customer>();

   if( CollectionUtils.isNotEmpty( addressList ) ){
        for( Address address : addressList )
        {
            customerData.add( this.dozerBeanMapper.map( address, Customer.class ) );
        }
   }
   return customerData;
}

CustomerData.java :客户数据.java :

Has instance field 'address' of type String

Address.java地址.java

Has instance field 'mainLocation' of type String

Currently I am using for loop to map each object of Address with Customer, how can I directly map addressList with customerData (list to list) without looping.目前我正在使用 for 循环将 Address 的每个对象与 Customer 映射,如何直接将addressListcustomerData (列表到列表)映射而不循环。 Can someone please help me with the xml file changes for this logic.有人可以帮我更改此逻辑的 xml 文件吗?

As far as I remember there was no possibility to map a Collection to a Collection in Dozer.据我所知,在 Dozer 中不可能将集合映射到集合。 You need to iterate over it.你需要迭代它。 Take a look at this closed issue and the reason: https://github.com/DozerMapper/dozer/issues/5看看这个关闭的问题和原因: https : //github.com/DozerMapper/dozer/issues/5

What you could do to ease the pain would be using Java 8 (if you can) or Guava for some more declarative way of handling that mapping.您可以做些什么来减轻痛苦,那就是使用 Java 8(如果可以的话)或 Guava 来处理该映射的一些更具声明性的方式。

Java 8 example: Java 8 示例:

<FROM, TO> List<TO> mapList(List<FROM> fromList, final Class<TO> toClass) {
    return fromList
            .stream()
            .map(from -> this.dozerBeanMapper.map(from, toClass))
            .collect(Collectors.toList());
}

Guava example:番石榴示例:

<FROM, TO> List<TO> mapList(List<FROM> fromList, final Class<TO> toClass) {
    return Lists.transform(fromList, new Function<FROM, TO>() {
        @Override
        public TO apply(FROM from) {
            return this.dozerBeanMapper(from, toClass);
        }
    });
}

Hi I think this could be useful, thanks @gmaslowski for the idea:嗨,我认为这可能很有用,感谢 @gmaslowski 的想法:

/**
 * @param <T>
 * @param <V>
 * @param fromList list source objects
 * @param toClass target class objects
 * @param mapperId map-id in to dozer-mapping file 
 * @return list of toClass mapped 
 */
public <T, V> List<V> mapList(List<T> fromList, Class<V> toClass, String mapperId) {
    return fromList.stream().map(from -> {
        try {
            return this.dozerBean.getObject().map(from, toClass, mapperId);
        } catch (Exception e) {
            log.error("Error Dozer Mapping Objects {}", e.getMessage());
        }
        return null;
    }).collect(Collectors.toList());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM