• JAVA集合07_关于sorted如何排序、实战三级分类树状展示


    ①. Stream.sorted字段排序

    • ①. sorted() 默认使用自然序排序, 其中的元素必须实现Comparable接口

    • ②. sorted(Comparator comparator) :我们可以使用lambada来创建一个Comparator实例。可以按照升序或着降序来排序元素

    • ③. 常用方法展示:

    // 默认升序
    list.stream().sorted() 
     
    // 自然序逆序元素,使用Comparator 提供的reverseOrder() 方法 降序
    list.stream().sorted(Comparator.reverseOrder()) 
     
    // 使用Comparator 来排序一个list
    list.stream().sorted(Comparator.comparing(Student::getAge)) 
     
    // 颠倒使用Comparator 来排序一个list的顺序,使用Comparator 提供的reverseOrder() 方法
    list.stream().sorted(Comparator.comparing(Student::getAge).reversed()) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • ④. 测试代码
    // User[id; age; name; Info[salary]]
    List<User> lists = Lists.newArrayList();
    lists.add(new User(1, 24, "张三", new Info("7000")));
    lists.add(new User(2, 22, "李四", new Info("8500")));
    lists.add(new User(3, 24, "王五", new Info("9000")));
    
    //  整形集合
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    
    // 按年龄升序
    List<User> userList = lists.stream()
           .sorted(Comparator.comparing(User::getAge))
           .collect(Collectors.toList());
    
    List<Integer> numberList = numbers.stream()
           .sorted(Comparator.comparing(Integer::intValue))
           .collect(Collectors.toList());
    
    // 按年龄降序
    List<User> userList = lists.stream()
           .sorted(Comparator.comparing(User::getAge).reversed())
           .collect(Collectors.toList());
    
    List<Integer> numberList = numbers.stream()
           .sorted(Comparator.comparing(Integer::intValue).reversed())
           .collect(Collectors.toList());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    ②. thenComparing多字段排序

    • ①. 通过Comparator.thenComparing(Comparator other) 实现

    • ②. 先以年龄升序,当年龄相同时,以薪资升序

     // 关键字thenComparing
     //  1.先以年龄升序  2.当年龄相同时,在以薪资升序
     List<User> userList = lists.stream()
             .sorted(Comparator.comparing(User::getAge).thenComparing(User::getSalary))
             .collect(Collectors.toList());
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • ③. 多字段即升序又降序排序
    // 关键 thenComparing、Comparator.reverseOrder()
    //  1.先以年龄升序  2.当年龄相同时,在以薪资降序
    List<User> userList = lists.stream()
            .sorted(Comparator.comparing(User::getAge).thenComparing(User::getSalary,Comparator.reverseOrder()))
            .collect(Collectors.toList());
    
    • 1
    • 2
    • 3
    • 4
    • 5

    ③. 三级分类树状展示

    • ①. 表结构如下
      在这里插入图片描述

    • ②. 按照如下的json格式展示,并且要求按照parent_code(升序),sort(升序),modify_time DESC(降序)

    [
    	{
    		"categoryType": "LIBRARY",
    		"childList": [
    			{
    				"categoryType": "LIBRARY",
    				"code": "200200",
    				"id": "5f1a559e3a36990001bf24e1",
    				"modifyTime": 1598593435000,
    				"name": "清热解毒",
    				"nodeLevel": 1,
    				"parentCode": "100017",
    				"shopCode": "YD-5e79a51c28a3200001d9e719",
    				"shopMerchant": "5e79a51c28a3200001d9e719",
    				"sort": 0,
    				"status": true
    			},
    			{
    				"categoryType": "LIBRARY",
    				"code": "200197",
    				"id": "5f1a559e3a36990001bf24e2",
    				"imgUrl": "",
    				"modifyTime": 1598593435000,
    				"name": "感冒药",
    				"nodeLevel": 1,
    				"parentCode": "100017",
    				"shopCode": "YD-5e79a51c28a3200001d9e719",
    				"shopMerchant": "5e79a51c28a3200001d9e719",
    				"sort": 1,
    				"status": true
    			},
    			{
    				"categoryType": "LIBRARY",
    				"code": "200291",
    				"id": "5f1a559e3a36990001bf24e3",
    				"modifyTime": 1598593435000,
    				"name": "其他",
    				"nodeLevel": 1,
    				"parentCode": "100017",
    				"shopCode": "YD-5e79a51c28a3200001d9e719",
    				"shopMerchant": "5e79a51c28a3200001d9e719",
    				"sort": 2,
    				"status": true
    			},
    			{
    				"categoryType": "LIBRARY",
    				"code": "200199",
    				"id": "5f1a559e3a36990001bf24e5",
    				"modifyTime": 1598593436000,
    				"name": "消炎药",
    				"nodeLevel": 1,
    				"parentCode": "100017",
    				"shopCode": "YD-5e79a51c28a3200001d9e719",
    				"shopMerchant": "5e79a51c28a3200001d9e719",
    				"sort": 4,
    				"status": true
    			}
    		],
    		"code": "100017",
    		"id": "5f1a559e3a36990001bf24e6",
    		"imgUrl": "",
    		"modifyTime": 1650966344000,
    		"name": "常备用药",
    		"nodeLevel": 0,
    		"shopCode": "YD-5e79a51c28a3200001d9e719",
    		"shopMerchant": "5e79a51c28a3200001d9e719",
    		"sort": 0,
    		"status": true
    	}
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    	public List<GoodsCategory> getGoodsCategoryList(......) {
    		// .....前面步骤就省略了,parentCategorieList获取到的是表中的所有数据
    		List<GoodsCategory> parentCategorieList = collect.stream().filter((entity) -> {
                        return entity.getParentCode() == null;
                    }).map((item) -> {
                        item.setChildList(getChilder(item, collect));
                        return item;
                        //order by  parent_code,sort,modify_time DESC
                    })
                    //(1). 对parentCode进行升序
                    .sorted((menu1,menu2)->{
                        return menu1.getParentCode()==null?0:menu1.getParentCode().length()-(menu2.getParentCode()==null?0:menu2.getParentCode().length());
                    })
    //                .sorted((menu1,menu2)->{
    //                    return menu1.getSort()==null?0:menu1.getSort()-(menu2.getSort()==null?0:menu2.getSort());
    //                })
                    //(2). 在sort相同的情况下,对modifyTime进行降序排列
                    .sorted(Comparator.comparingInt(GoodsCategory::getSort).thenComparing(GoodsCategory::getModifyTime,Comparator.reverseOrder()))
                    //.sorted(Comparator.comparing(GoodsCategory::getModifyTime).reversed())
                    .collect(Collectors.toList());
            return parentCategorieList;
       private List<GoodsCategory> getChilder(GoodsCategory root, List<GoodsCategory> goodsCategoryList) {
            List<GoodsCategory> collect = goodsCategoryList.stream()
                    .filter(entity -> {
                        return root.getCode().equals(entity.getParentCode());
                    }).map((item) -> {
                        if(!CollectionUtils.isEmpty(getChilder(item, goodsCategoryList))){
                            item.setChildList(getChilder(item, goodsCategoryList));
                        }
                        return item;
                    })
                    .sorted((menu1,menu2)->{
                        return menu1.getParentCode()==null?0:menu1.getParentCode().length()-(menu2.getParentCode()==null?0:menu2.getParentCode().length());
                    })
    //                .sorted((menu1,menu2)->{
    //                    return menu1.getSort()==null?0:menu1.getSort()-(menu2.getSort()==null?0:menu2.getSort());
    //                })
                    .sorted(Comparator.comparingInt(GoodsCategory::getSort).thenComparing(GoodsCategory::getModifyTime,Comparator.reverseOrder()))
                    .collect(Collectors.toList());
            return collect;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    ④. 三级分类树状展示2

    • ①. 数据库表结果如下:

    在这里插入图片描述

    • ②. 使用java8新特性查找三级联洞并封装成树形结构
    @RestController
    @RequestMapping("product/category")
    public class CategoryController {
        @Autowired
        private CategoryService categoryService;
        /**
         * 查出所有分类、以及子分类,以树形结构组装起来
         */
        @RequestMapping("/list/tree")
        //@RequiresPermissions("product:category:list")
        public R list(){
            List<CategoryEntity> entities = categoryService.listWithTree();
            return R.ok().put("data", entities);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
       @Override
        public List<CategoryEntity> listWithTree() {
            //1、查出所有分类
            List<CategoryEntity> entities = baseMapper.selectList(null);
            //2、组装成父子的树形结构
            //2.1)、找到所有的一级分类
            List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                    categoryEntity.getParentCid() == 0
            ).map((menu)->{
                menu.setChildren(getChildrens(menu,entities));
                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 -> {
                //1、找到子菜单
                categoryEntity.setChildren(getChildrens(categoryEntity,all));
                return categoryEntity;
            }).sorted((menu1,menu2)->{
                //2、菜单的排序
                return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
            }).collect(Collectors.toList());
    
            return children;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    @Data
    @TableName("pms_category")
    public class CategoryEntity implements Serializable {
    	private static final long serialVersionUID = 1L;
    	/**
    	 * 分类id
    	 */
    	@TableId
    	private Long catId;
    	/**
    	 * 分类名称
    	 */
    	private String name;
    	/**
    	 * 父分类id
    	 */
    	private Long parentCid;
    	/**
    	 * 层级
    	 */
    	private Integer catLevel;
    	/**
    	 * 是否显示[0-不显示,1显示]
    	 */
    	@TableLogic(value = "1",delval = "0")
    	private Integer showStatus;
    	/**
    	 * 排序
    	 */
    	private Integer sort;
    	/**
    	 * 图标地址
    	 */
    	private String icon;
    	/**
    	 * 计量单位
    	 */
    	private String productUnit;
    	/**
    	 * 商品数量
    	 */
    	private Integer productCount;
    	@TableField(exist = false)
    	private List<CategoryEntity>children;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    在这里插入图片描述

  • 相关阅读:
    C++14 新特性
    LeetCode(力扣)37. 解数独Python
    RequestMappingHandlerAdapter类简介说明
    Switch 块、Switch 表达式、Switch 模式匹配,越来越好用的 Switch
    Comparable和Comparator的区别
    Java 基础常见知识点&面试题总结(上),2022 最新版!| JavaGuide
    【23种设计模式】装饰模式(九)
    TCL 学习笔记
    LD_LIBRARY_PATH 环境变量设置
    如何拥有自己的私有docker仓库
  • 原文地址:https://blog.csdn.net/TZ845195485/article/details/126088512