List<T>转List<U>"/>
泛型实现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;}
更多推荐
泛型实现List<T>转List<U>
发布评论