java之list对象拷贝

java之list对象拷贝,第1张

springboot项目中经常会使用对象拷贝, 比如DTO转entity, entity转VO返回前端

单个对象常用的工具类有很多, 比如

#hutool
cn.hutool.core.bean.BeanUtil
#spring自带
org.springframework.beans.BeanUtils

开发过程中经常遇到的list对象拷贝时, 可能有些同学会循环去处理

List<UserDTO> userList;
List<UserEntity> resultList = new ArrayList<>();
for (UserDTO user : userList) {
    UserEntity userEntity= new UserEntity();
    BeanUtil.copyProperties(user, userEntity);
    resultList .add(userEntity);
}
return resultList;

整个过程可以封装成如下工具类CopyUtil

public static <S, T> List<T> copyList(List<S> sources, Supplier<T> target) {
    List<T> list = new ArrayList<>(sources.size());
    for (S source : sources) {
        T t = target.get();
        BeanUtils.copyProperties(source, t);
        list.add(t);
    }
    return list;
}

以上的场景就可以写成, 简化开发

// 入参List userList
return CopyUtil.copyList(userList, UserEntity::new);

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/917465.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存