Java的Map.Entry的方式实现Map树

构造Map的方式树形结构,使用Map.Entry的方式实现

	private void testDept(){
        String jsonStr="[{\"id\":1,\"name\":\"晨晨\",\"order\":100000000," +
                "\"parentId\":0},{\"id\":2,\"name\":\"小晨晨\",\"order\":100000000,\"parentId\":1},{\"id\":3,\"name\":\"大晨晨\",\"order\":99999000,\"parentId\":1}]";
        Map three = getThree(jsonStr,1);
        System.out.println(three);
    }
    private static Map getThree(String jsonStr,int parentId){

        List<Map> maps = JSONArray.parseArray(jsonStr, Map.class);
        HashMap<Integer, Map<String, Object>> map = new HashMap<>();
        HashMap<String, Object> map1= null;
        for (Map map2:maps) {
            String name = (String) map2.get("name");
            map1 = new HashMap<>();
            map1.put("pid",map2.get("parentId"));
            map1.put("dept_name",name);
            map1.put("name_index",name);
            map.put((Integer) map2.get("id"),map1);
        }
        //获取所有子节点
        Map childTree = getChildTree(map, parentId);
        Iterator<Map.Entry<Integer,Map<String,Object>>> iterator = childTree.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Integer,Map<String,Object>> next = iterator.next();
            getChildTree(childTree,next.getKey());
        }
        return map;
    }

    private static Map getChildTree(Map map,int id){
        Iterator<Map.Entry<String,Map<String,Object>>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Map<String, Object>> next = iterator.next();
            Map map1 = next.getValue();
            if(Integer.parseInt(map1.get("pid").toString())==id){
                map1.put("name_index", ((Map)map.get(id)).get("name_index")+">"+map1.get("dept_name"));
            }
        }
        return map;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值