JAVA实现树状图数据结构

 

一开始写数据的时候,感觉数据给原始数据即可,将存在parentId和id在一起的实体类集合一股脑的封装给前台,然后前端同事肯定使用的是树状图插件,将数据一股脑堆给插件,然后插件自动封装树等类型,感觉这样挺棒的...然后对接的前端同事告诉我,vue带的tree不是我想的那样..我也很尴尬.就封装个树给前台.无奈我也不会只能找java工具类了..哈哈哈...留作纪念..

 

package com.znzp.candidate.talentPool.req;

import com.huachan.talentPool.entity.ZnTalentpoolConfig;
import sun.reflect.generics.tree.Tree;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: app
 * @description
 * @author: Young
 * @create: 2020-10-28 19:44
 **/
public class TreeUtils {

    public List<ZnTalentpoolConfig> tree;
    public List<Object> list = new ArrayList<Object>();

    public List<Object> treeMenu(List<ZnTalentpoolConfig> tree) {
        this.tree = tree;
        for (ZnTalentpoolConfig treeNode : tree) {
            Map<String, Object> mapArr = new LinkedHashMap<String, Object>();
            if (treeNode.getParentId().equals("0")) {
                setTreeMap(mapArr, treeNode);
                list.add(mapArr);
            }
        }
        return list;
    }

    public List<?> child(String id) {
        List<Object> lists = new ArrayList<Object>();
        for (ZnTalentpoolConfig a : tree) {
            Map<String, Object> childArray = new LinkedHashMap<String, Object>();
            if (a.getParentId().equals(id)) {
                setTreeMap(childArray, a);
                lists.add(childArray);
            }
        }
        return lists;
    }

    private void setTreeMap(Map<String, Object> mapArr, ZnTalentpoolConfig treeNode) {
        mapArr.put("id", treeNode.getTalentpoolId());
        mapArr.put("name", treeNode.getTalentpoolName());
        mapArr.put("parentId", treeNode.getParentId());
        List<?> children = child(treeNode.getTalentpoolId());
        if (children.size() > 0) {
            mapArr.put("hasChild", true);
        } else {
            mapArr.put("hasChildren", false);
        }
        mapArr.put("children", child(treeNode.getTalentpoolId()));
    }
}

List中到底是什么,可以根据自己的需求来改,map也可,object也行...但是id和parentId要对应的上才有道理.

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页