泛型实现List<T>转List<U>

[TOC]@TOC

泛型实现List<T>转List<U>

  • 支持T和U的属性名一致,调用converListT2ListU(List source, Class u)
  • 支持T和U的属性名不一致,调用converListT2ListU(List source, Class u, String relationFields)

用代码说话

 /**
     * 将List<T>转为List<U>,T和U赋值的属性名必须一致(底层采用Spring的BeanUtils.copyProperties实现)
     */
    public static <T, U> List<U> converListT2ListU(List<T> source, Class<U> u) {
        return converListT2ListU(source, u, null);
    }

    /**
     * 将List<T>转为List<U>,T和U赋值的属性名可以不一致(底层采用Jdk的PropertyDescriptor实现)
     * 如果T和U的属性不一致,可以通过 relationFields 设置
     * 说明:relationFields = "parentId:pid,id,name:userName" 表示T{parentId,id,name}映射为U{pid,id,userName}
     */
    public static <T, U> List<U> converListT2ListU(List<T> source, Class<U> u, String relationFields) {
        if (ObjectUtils.isEmpty(source)) return new ArrayList<>();

        if (ObjectUtils.isEmpty(relationFields)) return source.stream().map(e -> {
            try {
                U instanceU = u.newInstance();
                BeanUtils.copyProperties(e, instanceU);
                return instanceU;
            } catch (Exception e1) {
                return null;
            }
        }).collect(Collectors.toList());

        Map<String, String> relationMap = convertRelationFields2Map(relationFields);
        List<String> sourceQueryFields = relationMap.keySet().stream().collect(Collectors.toList());
        return source.stream().map(e -> {
            try {
                U instanceU = u.newInstance();
                for (String sourceQueryField : sourceQueryFields) {
                    PropertyDescriptor sourcePD = new PropertyDescriptor(sourceQueryField, e.getClass());
                    PropertyDescriptor targetPD = new PropertyDescriptor(relationMap.get(sourceQueryField), instanceU.getClass());
                    targetPD.getWriteMethod().invoke(instanceU, sourcePD.getReadMethod().invoke(e));
                }
                return instanceU;
            } catch (Exception e1) {
                return null;
            }
        }).collect(Collectors.toList());
    }

    /**
     * 将属性关系字符串格式转换为Map格式,如:"parentId:pid,id,name:userName"转换为Map={parentId=pid,id=id,name=userName}
     *
     * @param relationFields 属性关系,字符串格式
     * @return 属性关系map格式
     */
    private static Map<String, String> convertRelationFields2Map(String relationFields) {
        Map<String, String> resultMap = new HashMap<>();
        String[] relationFieldArr = relationFields.split(",");
        for (String relationField : relationFieldArr) {
            String[] fieldArr = relationField.split(":");
            resultMap.put(fieldArr[0], fieldArr.length == 1 ? fieldArr[0] : fieldArr[1]);
        }
        return resultMap;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值