美文网首页Java
[Java]用Lambda构建父子级菜单

[Java]用Lambda构建父子级菜单

作者: AbstractCulture | 来源:发表于2021-12-27 17:05 被阅读0次
        public List<MenuDTO> getMenus() {
            List<MenuEntity> menuEntityList = list();
            if (CollectionUtils.isEmpty(menuEntityList)) {
                return Collections.emptyList();
            }
            List<MenuDTO> menuDTOList = BeanUtils.copyProperties(menuEntityList, MenuDTO.class);
            List<MenuDTO> resultDTOs = menuDTOList.stream()
                    .filter(m -> m.getParentId() == 0)
                    .peek(m -> m.setChildrenMenuDTOs(getChildMenus(m, menuDTOList)))
                    .sorted(Comparator.comparing(MenuDTO::getSort))
                    .collect(Collectors.toList());
            return resultDTOs;
        }
    
        private List<MenuDTO> getChildMenus(MenuDTO menuDTO, List<MenuDTO> menuDTOList) {
            return menuDTOList.stream()
                    .filter(m -> Objects.equals(m.getParentId(), menuDTO.getId()))
                    .peek(m -> m.setChildrenMenuDTOs(getChildMenus(m, menuDTOList)))
                    .sorted(Comparator.comparing(MenuDTO::getSort))
                    .collect(Collectors.toList());
        }
    
    • MenuDTO
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public class MenuDTO {
        @ApiModelProperty("菜单id")
        private Long id;
        @ApiModelProperty("菜单名称")
        private String name;
        @ApiModelProperty("菜单路径")
        private String url;
        @ApiModelProperty("菜单图标")
        private String icon;
        @ApiModelProperty("前端菜单索引")
        private String frontIndex;
        @ApiModelProperty("排序")
        private Integer sort;
        @ApiModelProperty("父级ID")
        private Long parentId;
        @ApiModelProperty("子菜单")
        private List<MenuDTO> childrenMenuDTOs;
    }
    
    

    DDDD

    相关文章

      网友评论

        本文标题:[Java]用Lambda构建父子级菜单

        本文链接:https://www.haomeiwen.com/subject/urbyqrtx.html