【java】关于Map的排序性的一次使用,有序的Map

本文介绍如何使用有序Map(TreeMap)根据商品分类ID获取其层级信息。通过将商品分类ID转换为List并利用TreeMap进行排序,可以有效地展示商品分类的层级结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于Map的排序性的一次使用,有序的Map

>>>>>

hashmap是按key的hash码排序的,而treemap是利用comparator 进行key的自然排序的

 

/**
     * 根据商品分类ID
     * 获取长编码,拿到向上的所有父级商品分类ID
     *
     * 根据parentUidList  获取 parentList
     *
     * 迭代parentUid 根据uid 获取在有序List中的 下标
     *
     * 按照[k:v][下标:具体信息]
     * 放入TreeMap 即得到有序的父层商品分类层级信息
     * @param entity
     * @return
     */
    @Override
    public AjaxResult<Map<Integer, GoodsTypeSimpleBean>> findGoodsTypeTree(GoodsType entity) {
        LunaResultBean.checkField(entity,"uid");
        TenementUser tenementUser = RequestData.TENEMENT_USER.get();
        AjaxResult<Map<Integer,GoodsTypeSimpleBean>> res = new AjaxResult<>();
        GoodsType goodsType = goodsTypeService.get(entity.getUid());
        if (goodsType != null && tenementUser.getTenementId().equals(goodsType.getTenementId())){
            String longCode = goodsType.getLangCode();
            List<String> parentUidList = Arrays.asList(longCode.split(":"));
            List<GoodsType> parentList = goodsTypeService.findByUidIn(parentUidList);

            Map<Integer,GoodsTypeSimpleBean> sortMap = new TreeMap<>();
            for (GoodsType type : parentList) {
                GoodsTypeSimpleBean bean = new GoodsTypeSimpleBean();
                bean.setGoodsTypeName(type.getName());
                bean.setOuterCode(type.getOuterCode());

                int index = parentUidList.indexOf(type.getUid())+1;
                sortMap.put(index,bean);
            }

            res.initTrue(sortMap);
        }else {
            res.initFalse("商品分类不存在",LunaResultBean.ERROR_BUSINESS);
        }
        return res;
    }
View Code

 

获取结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值