联合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: []
}]
};
以上,拷贝本地运行,任意应用。
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/192342.html