实体类代码:
@Data
public class AcAppRoleMenuDto {
/**
* 菜单编码
*/
private String menuCode;
/**
* 菜单名称
*/
private String menuName;
/**
* 排序
*/
private Integer orderValue;
/**
* 父菜单id, 0 表示顶级菜单
*/
private Long parentId;
/**
* 角色名称
*/
private String roleName;
/**
* 菜单id
*/
private Long appMenuId;
/**
* 角色id
*/
private Integer appRoleId;
/**
* 子节点
*/
private List<AcAppRoleMenuDto> childrenList;
}
把list菜单转为Map
/**
* 把list菜单转为Map
*
* @param menuList 菜单树组装之前平级且乱序的菜单list
* @return
*/
private Map<Long, AcAppRoleMenuDto> listAcAppMenuToMap(List<AcAppRoleMenuDto> menuList) {
//指定HashMap初始容量,减少扩容的次数,初始容量大小根据具体情况而定
Map<Long, AcAppRoleMenuDto> map = new HashMap<>(3000);
if (CollUtil.isNotEmpty(menuList)) {
for (AcAppRoleMenuDto appMenuDto : menuList) {
//appMenuId必须是唯一的才可以作为map的key
Long appMenuId = appMenuDto.getAppMenuId();
if (appMenuId != null) {
map.put(appMenuId, appMenuDto);
}
}
}
return map;
}
把菜单组装成一棵树
/**
* 把菜单组装成一棵树
*
* @param menuList
* @return
*/
private List<AcAppRoleMenuDto> treeAcAppRoleMenuDto(List<AcAppRoleMenuDto> menuList) {
List<AcAppRoleMenuDto> menuDtoResultList = new ArrayList<>(3000);
if (CollUtil.isNotEmpty(menuList)) {
Map<Long, AcAppRoleMenuDto> menuDtoMap = this.listAcAppMenuToMap(menuList);
for (AcAppRoleMenuDto appRoleMenuDto : menuList) {
Long appMenuId = appRoleMenuDto.getAppMenuId();
Long parentId = appRoleMenuDto.getParentId();
if (appMenuId != null && parentId != null) {
if (parentId == 0) {
menuDtoResultList.add(appRoleMenuDto);
} else {
AcAppRoleMenuDto appRoleMenuParent = menuDtoMap.get(parentId);
if (appRoleMenuParent != null) {
List<AcAppRoleMenuDto> childrenList = appRoleMenuParent.getChildrenList();
if (childrenList == null) {
childrenList = new ArrayList<>();
appRoleMenuParent.setChildrenList(childrenList);
}
childrenList.add(appRoleMenuDto);
}
}
}
}
}
return menuDtoResultList;
}
把菜单树转为平级的list
/**
* 把树转为平级的list
*
* @param treeMenuList
* @param menuList
* @return
*/
private List<AcAppRoleMenuDto> treeToLevelAcAppRoleMenu(List<AcAppRoleMenuDto> treeMenuList, List<AcAppRoleMenuDto> menuList) {
if (CollUtil.isNotEmpty(treeMenuList)) {
for (AcAppRoleMenuDto appRoleMenuDto : treeMenuList) {
menuList.add(appRoleMenuDto);
List<AcAppRoleMenuDto> childrenList = appRoleMenuDto.getChildrenList();
if (CollUtil.isNotEmpty(childrenList)) {
this.treeToLevelAcAppRoleMenu(childrenList, menuList);
}
}
}
return menuList;
}
应用场景
把菜单树转为平级的list 应用场景
适用于同步自己系统的菜单到其他系统,或者把其他系统的菜单同步到自己的系统