java Stream

2023-06-12  本文已影响0人  AGEGG

ex1

@Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);

        List<CategoryEntity> level1Menus = categoryEntityList.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            menu.setChildren(getChildrens(menu, categoryEntityList));
            return menu;
        }).sorted((menu1, menu2)->{
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((categoryEntity)->{
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2)->{
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

分组排序(倒序):

Map<String, List<TargetInfoDto>> groupData = list.stream()
                    .sorted(Comparator.comparing(TargetInfoDto::getAreaNum, Comparator.nullsLast(Comparator.reverseOrder())))
                    .collect(Collectors.groupingBy(TargetInfoDto::getGroupCode, LinkedHashMap::new, Collectors.toList()));

上一篇下一篇

猜你喜欢

热点阅读