您好,登錄后才能下訂單哦!
聯合MyBatis,由Map獲取
源碼如下
package com.zl.demo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Java遞歸獲取TreeJson
* @author ZhangLi
* @date 2019年6月18日 上午11:10:45
* @WeiXin zl4828
* @備注 沫沫金原創提供,僅供參考
*/
public class TreeJson {
public static void main(String[] args) {
TreeJson treeJson = new TreeJson();
treeJson.treeMap.add(new HashMap<String, Object>(){{
put("ID","0");
put("NAME","根節點");
put("PID","null");
}});
treeJson.treeMap.add(new HashMap<String, Object>(){{
put("ID","1");
put("NAME","節點1");
put("PID","0");
}});
treeJson.treeMap.add(new HashMap<String, Object>(){{
put("ID","2");
put("NAME","節點2");
put("PID","0");
}});
treeJson.treeMap.add(new HashMap<String, Object>(){{
put("ID","3");
put("NAME","節點3");
put("PID","0");
}});
treeJson.treeMap.add(new HashMap<String, Object>(){{
put("ID","11");
put("NAME","節點11");
put("PID","1");
}});
treeJson.treeMap.add(new HashMap<String, Object>(){{
put("ID","12");
put("NAME","節點12");
put("PID","1");
}});
treeJson.treeMap.add(new HashMap<String, Object>(){{
put("ID","13");
put("NAME","節點13");
put("PID","1");
}});
System.out.println(treeJson.recursiveTree("0"));
}
private List<Map<String, Object>> treeMap = new ArrayList<Map<String, Object>>(); //全局變量
/**
* 遞歸算法解析成樹形結構
* @param pid
*/
public Map recursiveTree(String pid) {
Map node = getNodeById(pid);
List<Map<String, Object>> childrenList = new ArrayList<Map<String, Object>>();
if(null==node){
return node;
}
List<Map<String, Object>> childTreeNodes = getChildTreeById(pid);
for(Map child : childTreeNodes){
Map n = recursiveTree(String.valueOf(child.get("ID")));
childrenList.add(n);
}
node.put("children",childrenList);
return node;
}
/**
* 根據pid查詢節點對象
*/
public Map getNodeById(String pid){
for (Map node : treeMap) {
if(null != pid){
if (pid.equals(node.get("ID"))) {
return node;
}
}
}
return null;
}
/**
* 根據父節點pid獲取所有了節點
*/
public List<Map<String, Object>> getChildTreeById(String pid){
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
if(null != treeMap){
for (Map node : treeMap) {
if(null != pid){
if (pid.equals(node.get("PID"))) {
list.add(node);
}
}
}
}
return list;
}
}
應用場景
例如,Echarts樹形圖形
注意,使用JSON轉換
{
name: '根節點',
pid: null,
id: 0,
children: [{
name: '節點1',
pid: 0,
id: 1,
children: [{
name: '節點11',
pid: 1,
id: 11,
children: []
}, {
name: '節點12',
pid: 1,
id: 12,
children: []
}, {
name: '節點13',
pid: 1,
id: 13,
children: []
}]
}, {
name: '節點2',
pid: 0,
id: 2,
children: []
}, {
name: '節點3',
pid: 0,
id: 3,
children: []
}]
};
以上,拷貝本地運行,任意應用。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。