优化后的代码如下:

public List<Tree> getUserAssociatedMenuList(String userId) { Set userAssociatedRoleIdSet = userRoleRelationService.lambdaQuery() .select(UserRoleRelation::getRoleId) .eq(UserRoleRelation::getUserId, userId) .list() .stream() .map(UserRoleRelation::getRoleId) .collect(Collectors.toSet());

//没有角色,则添加默认角色-基本用户
if (userAssociatedRoleIdSet.isEmpty()) {
    userAssociatedRoleIdSet.add("664025b2852045ceadf67cd759ae70ad");
}

//有管理员角色,则获取所有菜单,管理员权限默认取出所有菜单
boolean isAdministrator = userAssociatedRoleIdSet.contains("b7cf04c998c44ff1811db2224d898596");
Set<String> userAssociatedMenuIdSet = isAdministrator ? Collections.emptySet() : roleMenuRelationService.lambdaQuery()
        .select(RoleMenuRelation::getMenuId)
        .in(RoleMenuRelation::getRoleId, userAssociatedRoleIdSet)
        .list()
        .stream()
        .map(RoleMenuRelation::getMenuId)
        .collect(Collectors.toSet());

//关联的菜单为空直接返回
if (userAssociatedMenuIdSet.isEmpty() && !isAdministrator) {
    return Collections.emptyList();
}

List<Menu> menuList = this.lambdaQuery()
        .in(!isAdministrator, Menu::getId, userAssociatedMenuIdSet)
        .orderByAsc(Menu::getSort)
        .list();

return TreeUtil.build(menuList, "0", (menu, treeNode) -> {
    treeNode.setId(menu.getId());
    treeNode.setParentId(menu.getParentId());
    treeNode.setName(menu.getName());
    if (menu.getType().equals("菜单")) {
        treeNode.putExtra("isExternalUrl", menu.getIsExternalUrl());
        treeNode.putExtra("url", menu.getUrl());
        treeNode.putExtra("remark", menu.getRemark());
        treeNode.putExtra("tag", menu.getTag());
    }
});

}

优化点:

  1. 使用lambda表达式简化代码,避免冗长的匿名内部类语法。

  2. 使用Collections.emptySet()代替new HashSet<>(),因为空集合不需要修改,使用不可变集合可以提高性能。

  3. 简化代码逻辑,将一些if语句进行合并和简化,避免重复判断和分支。

  4. 使用MyBatis-Plus的lambdaQuery()方法进行查询,避免手动拼接SQL语句,提高代码可读性和维护性。

使用Collections.emptySet()和new HashSet<>()的区别在于,前者返回的是一个不可变的空集合,不能添加元素,而后者返回的是一个可变的空集合,可以添加元素。在这段代码中,使用Collections.emptySet()更合适,因为在一些场景下需要使用不可变集合来提高性能或确保安全。

jdk18springboot2X项目依赖mapstructmybatis-plushutool数据库为oraclepublic ListTreeString getUserAssociatedMenuListString userId SetString userAssociatedRoleIdSet = userRoleRelationServicelist Wr

原文地址: http://www.cveoy.top/t/topic/b0Gf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录