先创建结果结构,然后直接getOrDefault,最后put。
private Map<String, Map<String, ResourceBean>> covertResourceToMap(List<ResourceDto> resourceList) {Map<String, Map<String, ResourceBean>> result = new HashMap<>();for (ResourceDto resourceDto : resourceList) {Map<String, ResourceBean> serviceCodeGroup = result.getOrDefault(resourceDto.getHotlineId(), new HashMap<>());ResourceBean resourceBean = serviceCodeGroup.getOrDefault(resourceDto.getServiceCode(), new ResourceBean());if (ResourceTypeEnum.MENU.getType().equals(resourceDto.getType())) {addMenuList(resourceBean, resourceDto);} else if (ResourceTypeEnum.PERMISSION.getType().equals(resourceDto.getType())) {addPermissionList(resourceBean, resourceDto);} else {log.warn("未知资源类型,resourceType:{}", resourceDto.getType());}serviceCodeGroup.put(resourceDto.getServiceCode(), resourceBean);result.put(resourceDto.getHotlineId(), serviceCodeGroup);}return result;}private void addMenuList(ResourceBean resourceBean, ResourceDto resourceDto) {List<MenuVO> menuList = Optional.ofNullable(resourceBean.getMenuList()).orElse(new ArrayList<>());MenuVO menuVO = new MenuVO();BeanUtils.copyProperties(resourceDto, menuVO);menuList.add(menuVO);resourceBean.setMenuList(menuList);}private void addPermissionList(ResourceBean resourceBean, ResourceDto resourceDto) {List<PermissionVO> permissionList = Optional.ofNullable(resourceBean.getPermissionList()).orElse(new ArrayList<>());PermissionVO permissionVO = new PermissionVO();BeanUtils.copyProperties(resourceDto, permissionVO);permissionList.add(permissionVO);resourceBean.setPermissionList(permissionList);}
相同结构的树与树之间进行信息填充转换递归方式
private static void buildMenuTreeByMenuIdVo(MenuIdVO menuIdVO, Map<String, String> resourceCache, MenuVO result) {ResourceEntity resourceEntity = JSONObject.parseObject(resourceCache.get(String.valueOf(menuIdVO.getId())),ResourceEntity.class);BeanUtils.copyProperties(resourceEntity, result);if (CollectionUtils.isEmpty(menuIdVO.getChildrenIds())) {return;}for (MenuIdVO m : menuIdVO.getChildrenIds()) {MenuVO menuVO = new MenuVO();buildMenuTreeByMenuIdVo(m, resourceCache, menuVO);Optional.ofNullable(result.getChildren()).orElse(new ArrayList<>()).add(menuVO);}}