0
点赞
收藏
分享

微信扫一扫

java 拷贝数组

践行数据分析 2022-02-15 阅读 137

1.定义一个函数式接口

@FunctionalInterface
public interface BeanUtilCopyCallBack <S, T> {

    /**
     * 定义默认回调方法
     * @param t
     * @param s
     */
    void callBack(S t, T s);
}

2.封装一个工具类 BeanUtilCopy.java

public class BeanUtilCopy extends BeanUtils {

    /**
     * 集合数据的拷贝
     * @param sources: 数据源类
     * @param target: 目标类::new(eg: UserVO::new)
     * @return
     */
    public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target) {
        return copyListProperties(sources, target, null);
    }


    /**
     * 带回调函数的集合数据的拷贝(可自定义字段拷贝规则)
     * @param sources: 数据源类
     * @param target: 目标类::new(eg: UserVO::new)
     * @param callBack: 回调函数
     * @return
     */
    public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target, BeanUtilCopyCallBack<S, T> callBack) {
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T t = target.get();
            copyProperties(source, t);
            list.add(t);
            if (callBack != null) {
                // 回调
                callBack.callBack(source, t);
            }
        }
        return list;
    }

}

3.测试

List userDOList = new ArrayList();
userDOList.add(new UserDO(1L, “Van”, 18, 1));
userDOList.add(new UserDO(2L, “VanVan”, 20, 2));
List userVOList = BeanUtilCopy.copyListProperties(userDOList, UserVO::new);
log.info(“userVOList:{}”,userVOList);

举报

相关推荐

0 条评论