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

关于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

获取结果如下:

原文地址:https://www.cnblogs.com/sxdcgaq8080/p/9959882.html