java后端递归树,机构树,遍历树
publicstaticvoidgetChildrenList(List
List
for(JSONObjectjo:list){
if(ing("pid").equals(ing("id"))){
(jo);
("children",getChildrenList(list,jo));
}
}
//returnretList;
("children",retList);
}
第⼀种,⽅法循环⼀次,⽐较耗费内存,不建议使⽤
publicstaticvoidmain(String[]args){
//拼装数据
List
(bject("{id:'1',name:'n1',pid:'-1'}"));
(bject("{id:'2',name:'n1',pid:'-1'}"));
(bject("{id:'3',name:'n1',pid:'-1'}"));
(bject("{id:'1-1',name:'n1-1',pid:'1'}"));
(bject("{id:'2-1',name:'n2-1',pid:'2'}"));
(bject("{id:'3-1',name:'n3-1',pid:'3'}"));
(bject("{id:'1-2',name:'n1-2',pid:'1'}"));
(bject("{id:'2-2',name:'n2-2',pid:'2'}"));
(bject("{id:'3-2',name:'n3-2',pid:'3'}"));
(bject("{id:'1-3',name:'n1-3',pid:'1'}"));
(bject("{id:'2-3',name:'n2-3',pid:'2'}"));
(bject("{id:'3-3',name:'n3-3',pid:'3'}"));
(bject("{id:'1-1-1',name:'n1-1-1',pid:'1-1'}"));
(bject("{id:'1-1-2',name:'n1-1-2',pid:'1-1'}"));
(bject("{id:'1-1-3',name:'n1-1-3',pid:'1-1'}"));
//递归根节点
JSONObjecttJo=bject("{id:'-1',name:'根节点'}");
//("children",getChildrenList(list,tJo));
n(String());
//⼀次循环⽅法,⽐较好内存不建议使⽤
Map
for(JSONObjectjo:list){
Stringpid=ing("pid");
Stringid=ing("id");
if(!nsKey(pid)){//不存在
(pid,newArrayList
}
(pid).add(jo);
if(!nsKey(id)){
(id,newArrayList
}
("children",(id));
}
JSONObjecttJo2=bject("{id:'-1',name:'根节点'}");
("children",("-1"));
n(String());
}
第⼆种⽅法,两次循环,建议使⽤,节省内存
publicstaticvoidmain(String[]args){
//拼装数据
List
(bject("{id:'1',name:'n1',pid:'-1'}"));
(bject("{id:'2',name:'n1',pid:'-1'}"));
(bject("{id:'3',name:'n1',pid:'-1'}"));
(bject("{id:'1-1',name:'n1-1',pid:'1'}"));
(bject("{id:'2-1',name:'n2-1',pid:'2'}"));
(bject("{id:'3-1',name:'n3-1',pid:'3'}"));
(bject("{id:'1-2',name:'n1-2',pid:'1'}"));
(bject("{id:'2-2',name:'n2-2',pid:'2'}"));
(bject("{id:'3-2',name:'n3-2',pid:'3'}"));
(bject("{id:'1-3',name:'n1-3',pid:'1'}"));
(bject("{id:'2-3',name:'n2-3',pid:'2'}"));
(bject("{id:'3-3',name:'n3-3',pid:'3'}"));
(bject("{id:'1-1-1',name:'n1-1-1',pid:'1-1'}"));
(bject("{id:'1-1-2',name:'n1-1-2',pid:'1-1'}"));
(bject("{id:'1-1-3',name:'n1-1-3',pid:'1-1'}"));
//递归
JSONObjecttJo=bject("{id:'-1',name:'根节点'}");
//("children",getChildrenList(list,tJo));
n(String());
//两次循环⽅法,建议使⽤
Map
for(JSONObjectjo:list){
Stringpid=ing("pid");
if(!nsKey(pid)){//不存在
(pid,newArrayList
}
(pid).add(jo);
}
for(JSONObjectjo:list){
Stringid=ing("id");
if(nsKey(id)){
("children",(id));
}
}
JSONObjecttJo1=bject("{id:'-1',name:'根节点'}");
("children",("-1"));
n(String());
}
本文发布于:2022-12-27 13:36:07,感谢您对本站的认可!
本文链接:http://www.wtabcd.cn/fanwen/fan/90/40629.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |