![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/40323034fc197310a5f84873d907c382.png)
// 构建层级列表
private List<EpAuthUserInfoResponse.Menu> transferMenus(List<?> menus) {
List<EpAuthUserInfoResponse.Menu> result = new ArrayList<>();
List<Map> menuTree = buildTree((List<Map>) menus, "0"); // 转成层级数据
dfsTree(menuTree, result); // DFS 遍历,遍历时转格式
return result;
}
public List<Map> buildTree(List<Map> inputList, String rootKey) {
// 以 parentKey 做索引
Map<Object, List<Map>> parentMap = inputList.stream().collect(Collectors.groupingBy((json) -> {
return json.get("superiorFunctionCode");
}));
// 遍历List,从parentMap中领养儿子
inputList.forEach(sub -> {
// 当前这个节点的所有儿子
List<Map> children = parentMap.get(sub.get("functionCode"));
sub.put("children", children);
});
// 找到根结点
List<Map> roots = inputList.stream().filter(v -> (String.valueOf(v.get("superiorFunctionCode")).equals(rootKey)))
.collect(Collectors.toList());
return roots;
}
// 深度优先遍历树,对所有途径节点转换为所需格式
// 对于每个节点,先将他转为Menu格式,如果他有children,他的children由dfs方法获得
// 如果没有children,则到达函数边界 直接添加至上一级的(传入的childrenList)中
public void dfsTree(List<Map> roots, List<EpAuthUserInfoResponse.Menu> childrenList) {
for (Map node : roots) {
// convert current node
EpAuthUserInfoResponse.Menu menu = convertNode(node);
childrenList.add(menu);
if (node.get("children") != null) {
List<EpAuthUserInfoResponse.Menu> currentNodeChildren = new ArrayList<>(); // 准备一个篮子装这个节点的children
dfsTree((List<Map>) node.get("children"), currentNodeChildren);
menu.setChildren(currentNodeChildren);
}
}
}
public EpAuthUserInfoResponse.Menu convertNode(Map entity) {
EpAuthUserInfoResponse.Menu menu = new EpAuthUserInfoResponse.Menu();
menu.setIndex((String) entity.get("id"));
menu.setRouter((String) entity.get("functionUrl"));
menu.setName((String) entity.get("functionName"));
menu.setNameEn((String) entity.get("menuNameEn"));
menu.setIcon((String) entity.get("menuIcon"));
menu.setImg((String) entity.get("menuImg"));
menu.setAlter((String) entity.get("menuAlter"));
menu.setOrder(StrUtil.toString(entity.get("menuOrder")));
menu.setMenuCode((String) entity.get("functionCode"));
menu.setIsHidden((String) entity.get("menuIsHidden"));
return menu;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6b8104c43e3d53175f08cbcff6870281.png)