util 类
import com.vo.ThreeVO;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MenuTreeUtil {
//已经被buildTree的list集合
private static List<ThreeVO> menuCommon = new ArrayList<>();
//返回给前端的NewTree List集合
private static List<Object> list = new ArrayList<Object>();
public static List<Object> menuList(List<ThreeVO> menu) {
menuCommon.clear();
list.clear();
menuCommon = menu;
// 通过遍历menu,找到父节点为0的节点,它是顶级父节点
// 然后调用menuChild,递归遍历所有子节点
for (ThreeVO threeVO : menu) {
Map<String, Object> mapArr = new LinkedHashMap<String, Object>();
if (threeVO.getPid().equals(0)) {
mapArr.put("id", threeVO.getId());
mapArr.put("name", threeVO.getName());
mapArr.put("pid", threeVO.getPid());
//遍历开始
mapArr.put("childList", menuChild(threeVO.getId()));
list.add(mapArr);
}
}
return list;
}
private static List<?> menuChild(Integer id) {
List<Object> lists = new ArrayList<Object>();
//继续遍历menu
for (ThreeVO threeVO : menuCommon) {
System.out.println(threeVO.toString());
Map<String, Object> childArray = new LinkedHashMap<String, Object>();
//找到父ID等于父节点ID的子节点
if (threeVO.getPid().equals(id)) {
childArray.put("id", threeVO.getId());
childArray.put("name", threeVO.getName());
childArray.put("pid", threeVO.getPid());
//向下递归
childArray.put("childList", menuChild(threeVO.getId()));
lists.add(childArray);
}
}
return lists;
}
}
实体类
public class ThreeVO {
@ApiModelProperty(value = "id")
Integer id;
@ApiModelProperty(value = "父id")
Integer pid;
@ApiModelProperty(value = "名称")
String name;
}
测试类
public static void main(String[] args) {
// 模拟数据库查询到的数据
ThreeVO three1 = new ThreeVO();
three1.setId(1);
three1.setPid(0);
three1.setName("省委书记");
ThreeVO three2 = new ThreeVO();
three2.setId(2);
three2.setPid(1);
three2.setName("市委书记");
ThreeVO three3 = new ThreeVO();
three3.setId(3);
three3.setPid(2);
three3.setName("县委书记");
List<ThreeVO> threeList = new ArrayList<>();
threeList.add(three2);
threeList.add(three1);
threeList.add(three3);
System.out.println("----从顶级节点开始转换树----");
List<Object> objectTreeList = MenuTreeUtil.menuList(threeList);
System.out.println(objectTreeList.toString());
}
执行结果
[{id=1, name=省委书记, pid=0,
childList=[{id=2, name=市委书记, pid=1,
childList=[{id=3, name=县委书记, pid=2, childList=[]}]}]}]