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

编程入门 行业动态 更新时间:2024-10-09 23:18:02

泛型实现<a href=https://www.elefans.com/category/jswz/34/1770381.html style=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>

本文发布于:2024-03-07 08:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1717366.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:List

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!