java将集合中的数据转成树形结构

我这里的需求是,根据name进行模糊查询,将获取到的集合进行处理,以树形结构返回给前端。
首先创建一个树形类:(我只粘贴主要代码)

public class Tree {
    private String id;
    private String pId;
    private String name;
    private String code;
    private String ip;
    private String pName;  // 节点层级
    private List<Tree> children = new ArrayList<Tree>();

    // 添加节点
    public void add(Tree node) {
        if ("0".equals(node.pId)) {
            this.children.add(node);
        } else if (node.pId.equals(this.id)) {
            node.setpName(this.name);
            this.children.add(node);
        } else {
            for (Tree tree : children) {
                tree.add(node);
            }
        }
    }
}

我这里有个一集合数据比如 list,这里要将这些数据处理一下找到最顶上的类,看这些数据有几个根节点。

	//这里就是封装数据,找到哪些是根节点,哪些不是根节点
	List<Tree> trees = new ArrayList<>();
    List<Tree> trees1 = new ArrayList<>();
    int count = 0;
    for (Object c : objects) { //找出哪些是根节点对象
        for (int i = 0; i < objects.size(); i++) {
            if (c.getParentStationId().equals(objects.get(i).getId())) {
                count++;
                break;
            }
        }
        if (count == 0) {
            trees.add(new Tree(c.getId(), c.getParentStationId(), c.getStationName(), c.getStationCode(), c.getIp(), null));
        } else {
            trees1.add(new Tree(c.getId(), c.getParentStationId(), c.getStationName(), c.getStationCode(), c.getIp(), null));
            count = 0;
        }
    }

		List<Tree> list = new ArrayList<>();
        for (Tree t : trees) { // 遍历根节点的Tree
            getTree(trees1, t);
            list.add(t);
        }

这是getTree方法,向根节点挂接子节点,递归实现:

public  void  getTree(List<Tree> cTrees, Tree pTree){

    List<Tree> temp = new ArrayList<>();
    for(int i = 0;i < cTrees.size();i++)
    {
        //这里可以使用Iterator
        if(cTrees.get(i).getpId().equals(pTree.getId())) {
            pTree.add(cTrees.get(i));
            temp .add(cTrees.get(i));
        };
    }

    cTrees.removeAll(temp );
    for(int i = 0;i < temp .size(); i++) {
        getTree(cTrees, temp .get(i));
    }
}

到这里就结束了。


版权声明:本文为weixin_40583191原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。