树形结构List转tree(泛型版+普通版)非递归

  public static List<TreeObj> listToTreeList(List<TreeObj> treeList) {
        if(CollectionUtils.isEmpty(treeList)){
            return treeList;
        }
        Map<Integer, List<TreeObj>> treeLevelMap = new HashMap<>();
        Map<String, List<TreeObj>> treeParentCodeMap = new HashMap<>();
        treeList.stream().forEach(x -> {
            //按照树等级分组
            listGroupByGetFun(treeLevelMap,x,x.getLevel());
            //按照父编码分组
            listGroupByGetFun(treeParentCodeMap,x,x.getParentCode());

        });
        List<TreeObj> rootTree = new ArrayList<>();
        //获取树的最大层级
        Integer maxLevel = treeLevelMap.entrySet().stream().map(x -> 
          x.getKey()).max(Integer::compareTo).get();
        int i = 1;
        //循环level
        while (i <= maxLevel) {
            List<TreeObj> currentTreeList = treeLevelMap.get(i);
            currentTreeList.stream().forEach(x -> {
                //设置子集合相当于 x.setChild(list);
                //把当前节点的子集合从treeParentCodeMap中取出通过setChild方法赋值。
                ArrayList<TreeObj> childList = (ArrayList<TreeObj>) 
                treeParentCodeMap.get(x.getCode());
                x.setChild(childList);
            });
            if (i == 1) {
                rootTree.addAll(currentTreeList);
            }
            i++;
        }
        return rootTree;
    }
    private static <K> void listGroupByGetFun(Map<K, List<TreeObj>> map,TreeObj obj,K key) {
        //分组方法(存储分组map,被分组对象)
        //分组属性
        if (key == null) {
            return;
        }
        if (!map.containsKey(key)) {
            map.put(key, new ArrayList<>());
        }
        map.get(key).add(obj);
    }

普通版本

 private static final int LEVEL_INDEX =0;
    private static final int CODE_INDEX =1;
    private static final int PARENT_CODE_INDEX =2;
    private static final int CHILD_LIST_INDEX =3;
    private static Method[] methods;

    public static<T> List<T> listToTreeList(List<T> treeList) {
        if(CollectionUtils.isEmpty(treeList)){
            return treeList;
        }
        Class<T> cls = (Class<T>) treeList.get(0).getClass();
        TreeAnnotations annotation = cls.getAnnotation(TreeAnnotations.class);
        if(null == annotation){
            return treeList;
        }
        TreeUtils.methods = getMethod(cls);
        Map<Integer, List<T>> treeLevelMap = new HashMap<>();
        Map<String, List<T>> treeParentCodeMap = new HashMap<>();
        treeList.stream().forEach(x -> {
            //按照树等级分组
            listGroupByGetFun(treeLevelMap, x, getLevel(x));
            //按照父编码分组
            listGroupByGetFun(treeParentCodeMap,x, getParentCode(x));

        });
        List<T> rootTree = new ArrayList<>();
        //获取最大层级数
        Integer maxLevel = treeLevelMap.entrySet().stream().map(x -> x.getKey()).max(Integer::compareTo).get();
        int i = 1;
        //循环level
        while (i <= maxLevel) {
            List<T> currentTreeList = treeLevelMap.get(i);
            currentTreeList.stream().forEach(x -> {
                //设置子集合相当于 x.setChild(list);
                //把当前节点的子集合从treeParentCodeMap中取出通过setChild方法赋值。
                List<T> childList = treeParentCodeMap.get(getCode(x));
                setChild(x,childList);
            });
            if (i == 1) {
                rootTree.addAll(currentTreeList);
            }
            i++;
        }
        return rootTree;
    }

    //这里为了可读性特意提取出来,后期可自行去留
    private static <T> Integer getLevel(T x){
        return (Integer) getMethod(methods,x,LEVEL_INDEX);
    }
    private static <T> String getParentCode(T x){
        return (String)getMethod(methods,x,PARENT_CODE_INDEX);
    }
    private static <T> String getCode(T x){
        return (String)getMethod(methods,x,CODE_INDEX);
    }
    private static <T> void setChild(T x,List<T> childList){
        setMethod(methods,x,CHILD_LIST_INDEX,childList);
    }

    private static <K,T> void listGroupByGetFun(Map<K, List<T>> map,T obj,K key) {
        //分组方法(存储分组map,被分组对象)
        //分组属性
        if (key == null) {
            return;
        }
        if (!map.containsKey(key)) {
            map.put(key, new ArrayList<>());
        }
        map.get(key).add(obj);
    }

    private static<T> void setMethod(Method[] methods,T t,int index,Object setValue){
        try {
            methods[index].invoke(t,setValue);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    private static<T> Object getMethod(Method[] methods,T t,int index){
        try {
            return methods[index].invoke(t);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
    private static<T> Method[] getMethod(Class<T> cls){
        Method[] methods = new Method[4];
        for(Field field:cls.getDeclaredFields()) {
            try {
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(),cls);
                if(field.isAnnotationPresent(LevelAnnotation.class)){
                    methods[LEVEL_INDEX] = pd.getReadMethod();
                }
                if(field.isAnnotationPresent(CodeAnnotation.class)){
                    methods[CODE_INDEX]= pd.getReadMethod();
                }
                if(field.isAnnotationPresent(ParentCodeAnnotation.class)){
                    methods[PARENT_CODE_INDEX]= pd.getReadMethod();
                }
                if(field.isAnnotationPresent(ChildListAnnotation.class)){
                    methods[CHILD_LIST_INDEX] = pd.getWriteMethod();
                }
            } catch (IntrospectionException e) {
                e.printStackTrace();
            }
        }
        return methods;
    }

泛型通用版本,这个可读性差点,可以先看普通版本再看这个泛型版本。

@Data
@TreeAnnotations()
public class TreeObj {
    private String name;
    @LevelAnnotation
    private Integer level;
    @CodeAnnotation
    private String code;
    @ParentCodeAnnotation
    private String parentCode;
    @ChildListAnnotation
    private ArrayList<TreeObj> child;

    @Override
    public String toString() {
        return "TreeTest{" +
                "name='" + name + '\'' +
                ", level=" + level +
                ", code='" + code + '\'' +
                ", parentCode='" + parentCode + '\'' +
                '}';
    }
}

测试树对象

 注解类就是名字不一样,其他都一样。注解的作用是标识出哪些字段是层级、哪些字段是code。

可以自己根据实际情况变更。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值