package com.aaa.util;
import com.aaa.controller.vm.MenuVM;
import com.aaa.entity.Menu;
import java.util.ArrayList;
import java.util.List;
/**
* 组装菜单树工具类
* Created by cws
* @author Administrator
*/
public class MenuTreeUtil {
public static MenuVM getTree(List<Menu> list) {
//判断是否有获取到数据
if (list == null || list.size() < 1) {
return null;
}
return buildTree(getRoot(list), list);
}
private static MenuVM buildTree(MenuVM pnode, List<Menu> nodes) {
List<MenuVM> childs = new ArrayList<>();
for (Menu tmp : nodes) {
if (pnode.getId().equals(tmp.getParentId())) {
childs.add(new MenuVM(tmp));
}
}
//二次递归遍历子节点
if (childs.size() > 0) {
pnode.setSubMenu(childs);
for (MenuVM ptmp : childs) {
buildTree(ptmp, nodes);
}
}
return pnode;
}
/**
* 获取一级目录
*
* @param list
*/
private static MenuVM getRoot(List<Menu> list) {
for (Menu po : list) {
if ("#".equals(po.getParentId())) {
return new MenuVM(po);
}
}
return null;
}
/**
* @param list
*/
public static List<MenuVM> getMenu(List<Menu> list) {
//判断是否有获取到数据
if (list == null || list.size() < 1) {
return null;
}
return getTree(list) == null ? null : getTree(list).getSubMenu();
}
}`
<</br>>
## 例如:
```/**
* 根据用户id查找权限树菜单
* @param userId
* @return
*/
@Override
public List<MenuVM> getMenu(String userId) {
List<Menu> menuList = baseMapper.selectMenuByUserId(userId);
return MenuTreeUtil.getMenu(menuList);
}`