guava-集合使用

之前给上游提供批量插入的接口时,遇到一个问题,需要将dto批量转换成data。
用apache、spring提供的单例转换需要循环,见http://www.cnblogs.com/kivi170806/p/8007057.html。这时guava就排上用场啦。
源码如下

public static <F, T> List<T> transform(List<F> fromList, Function<? super F, ? extends T> function) {
        return (List)(fromList instanceof RandomAccess?new Lists.TransformingRandomAccessList(fromList, function):new Lists.TransformingSequentialList(fromList, function));
    }

demo如下

List<Entity> entities = Lists.transform(dtos, new Function<DTO, Entity>() {
            @Override
            public Entity apply(DTO dto) {
                Entity entity = new Entity();
                BeanCopier beanCopier = BeanCopier.create(DTO.class, Entity.class, false);
                beanCopier.copy(dto, entity, null);
                return entity;
            }
        });

解决完这个问题之后,需要将转换后的进行过滤。这里遇到了java.util.ConcurrentModificationException的问题。这里可以用guava的filter。

           //filter这段逻辑是将过滤掉md5相同的entity.
        if (CollectionUtils.isNotEmpty(falledPromoEntities)) {
            promoEntities = newArrayList(filter(promoEntities, new Predicate<Entity>() {
                @Override
                public boolean apply(@Nullable Entity entity) {
                    for (Entity promoEntity : falledPromoEntities) {
                        if (entity.getMD5().equals(promoEntity.getMD5())) {
                            return false;
                        }
                    }
                    return true;
                }
            }));
        }
posted @ 2017-12-26 14:59  kivi2  阅读(416)  评论(2编辑  收藏  举报