构造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;
}