您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
联合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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。