天天看點

java 遞歸處理樹形結構資料

在實戰開發中經常有需要處理樹形菜單、樹形目錄等等等業務需求。而對于這種産品,在設計資料庫時也建議使用id<----->parentId的結構來做。但是最終前端顯示多用hightChart或者Echart插件來實作。是以在給前端資料時,最好的做法就是把資料庫結構話的資料處理成treeJson格式。本文就簡單介紹以遞歸方式處理此資料。

資料庫表結構

id name type parentId
1 root
2 a
3 b
4 c
5 d
6 e
7 f
8 g

最終想要的效果

java 遞歸處理樹形結構資料

image.png

java 遞歸實作代碼

package com.br.usercenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;

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

/**
 * @author jack cooper
 * @create 2017-09-15 16:53
 */
public class TreeRecursion {

    public static void main(String[] args) {

        Map<String,Node> nodes = new HashedMap();
        //模拟資料庫存儲樹結構
        nodes.put("1",new Node("1","root",1,"0"));
        nodes.put("2",new Node("2","a",1,"1"));
        nodes.put("3",new Node("3","b",1,"1"));
        nodes.put("4",new Node("4","c",1,"1"));
        nodes.put("5",new Node("5","d",1,"2"));
        nodes.put("6",new Node("6","e",1,"2"));
        nodes.put("7",new Node("7","f",1,"3"));
        nodes.put("8",new Node("8","g",1,"7"));
        System.out.println("result:" + JSON.toJSONString(getNodeJson("0",nodes)));
    }

    /**
     * 遞歸處理   資料庫樹結構資料->樹形json
     * @param nodeId
     * @param nodes
     * @return
     */
    public static JSONArray getNodeJson(String nodeId, Map<String,Node> nodes){

        //目前層級目前node對象
        Node cur = nodes.get(nodeId);
        //目前層級目前點下的所有子節點(實戰中不要慢慢去查,一次加載到集合然後慢慢處理)
        List<Node> childList = getChildNodes(nodeId,nodes);

        JSONArray childTree = new JSONArray();
        for (Node node : childList) {
            JSONObject o = new JSONObject();
            o.put("name", node.getName());
            o.put("type", node.getType());
            JSONArray childs = getNodeJson(node.getId(),nodes);  //遞歸調用該方法
            if(!childs.isEmpty()) {
                o.put("children",childs);
            }
            childTree.fluentAdd(o);
        }
        return childTree;
    }

    /**
     * 擷取目前節點的所有子節點
     * @param nodeId
     * @param nodes
     * @return
     */
    public static List<Node> getChildNodes(String nodeId, Map<String,Node> nodes){
        List<Node> list = new ArrayList<>();
        for (String key : nodes.keySet() ) {
            if(nodes.get(key).getParentId().equals(nodeId)){
                list.add(nodes.get(key));
            }
        }
        return list;
    }

}


class Node{
    public String id ;
    public String name;
    public Integer type;
    public String parentId;

    public Node(String id, String name, Integer type, String parentId) {
        this.id = id;
        this.name = name;
        this.type = type;
        this.parentId = parentId;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public String getParentId() {
        return parentId;
    }

    public void setParentId(String parentId) {
        this.parentId = parentId;
    }
}
           

最終結果json

[
    {
        "children": [
            {
                "children": [
                    {
                        "children": [
                            {
                                "name": "g",
                                "type": 1
                            }
                        ],
                        "name": "f",
                        "type": 1
                    }
                ],
                "name": "b",
                "type": 1
            },
            {
                "children": [
                    {
                        "name": "d",
                        "type": 1
                    },
                    {
                        "name": "e",
                        "type": 1
                    }
                ],
                "name": "a",
                "type": 1
            },
            {
                "name": "c",
                "type": 1
            }
        ],
        "name": "root",
        "type": 1
    }
]
           

用echart處理最終效果

通路

http://echarts.baidu.com/echarts2/doc/example/tree1.html

在左側json中找到data節點,将value替換成上述json。點選重新整理即可。