list原始数据
[
{name:"A一级菜单1",fid:"-1",id:"1"},
{name:"AA二级菜单1",fid:"1",id:"2"},
{name:"AAA三级菜单1",fid:"2",id:"3"},
{name:"AB二级菜单2",fid:"1",id:"4"},
{name:"B一级菜单2",fid:"-1",id:"5"},
{name:"BA二级菜单1",fid:"5",id:"6"}
]
递归后成树的数据
[
{fid=-1, children=[{fid=1,children=[{fid=2,children=[], name=AAA三级菜单1,id=3}], name=AA二级菜单1,id=2}, {fid=1,children=[],name=AB二级菜单2, id=4}], name=A一级菜单1, id=1},
{fid=-1, children=[{fid=5, children=[], name=BA二级菜单1, id=6}], name=B一级菜单2, id=5}
]
代码
/**
*
*/
package com.incon.project.mooc.moocXsxx.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 肖
* @version 创建时间:2020年4月10日 下午3:17:03
* 类说明
*/
/**
* @author Administrator
*
*/
public class ListTheRecursiveTree {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map map = new HashMap();
map.put("name", "A一级菜单1");map.put("fid", "-1");map.put("id", "1");
list.add(map);
map = new HashMap<>();
map.put("name", "AA二级菜单1");map.put("fid", "1");map.put("id", "2");
list.add(map);
map = new HashMap<>();
map.put("name", "AAA三级菜单1");map.put("fid", "2");map.put("id", "3");
list.add(map);
map = new HashMap<>();
map.put("name", "AB二级菜单2");map.put("fid", "1");map.put("id", "4");
list.add(map);
map = new HashMap<>();
map.put("name", "B一级菜单2");map.put("fid", "-1");map.put("id", "5");
list.add(map);
map = new HashMap<>();
map.put("name", "BA二级菜单1");map.put("fid", "5");map.put("id", "6");
list.add(map);
List trreList = getTree(list);
//如果返回前端需要json对象
// System.out.println(JSONArray.fromObject(trreList));
System.out.println(trreList);
}
/**
* @param plList 要格式的数据
* fid 父级id
* id 数据id
* @return
*/
static List<Map<String, Object>> getTree(List<Map<String, Object>> plList){
List<Map<String,Object>> MenuList = new ArrayList<Map<String, Object>>();
for(Map<String, Object> vo: plList){
if("-1".equals(vo.get("fid").toString())){//通过判断,-1代表父级,也就是一级
vo.put("children", getChildren(plList,vo.get("id").toString()));//继续往一级下面遍历,调用下面的处理方法,放入树状结构
MenuList.add(vo);//先把一级存入结果
}
}
return MenuList;
}
//结果集转树状结构
static List<Map<String, Object>> getChildren(List<Map<String, Object>> plList,String menuId){//参数为数据库的(原数据,一级id)
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
try {
if(plList==null||plList.size()==0||menuId==null){
return list;
}
for(Map<String, Object> vo:plList ){
if(menuId.equals(vo.get("fid").toString())){//如果本级id与下面数据的父id相同,就说明是子父级关系
vo.put("children", getChildren(plList,vo.get("id").toString()));//递归,查询子级下的子级
list.add(vo);
}
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return list;
}
}