- public static List<Map<String, Object>> buildTree(List<TreeNode> list) {
-
- List<Map<String, Object>> rootList = new ArrayList<Map<String, Object>>();
-
- Map<String, Map<String, Object>> rootMap = new HashMap<String, Map<String, Object>>();
-
- for (TreeNode node : list) {
-
- Integer acl = node.getAcl();
-
- Integer parentAcl = node.getParentAcl();
-
- Map<String, Object> newNode = createNode(acl);
-
- rootMap.put(acl + "", newNode);
-
- if (parentAcl.equals(-1)) {
-
- rootList.add(newNode);
-
- } else {
-
- Map<String, Object> fatherNode = rootMap.get(parentAcl + "");
-
- addChild(fatherNode, newNode);
-
- }
-
- }
-
- return rootList;
-
- }
-
-
-
- private static void addChild(Map<String, Object> father,
-
- Map<String, Object> child) {
-
- //如果father=null,一定是没有正确按照level排序导致的
-
- if (father == null) {
-
- System.out.println("error,Father is null");
-
- return;
-
- }
-
- Object o = father.get("children");
-
- List<Map<String, Object>> childs;
-
- if (o == null) {
-
- childs = new ArrayList<Map<String, Object>>();
-
- father.put("children", childs);
-
- } else {
-
- childs = (List<Map<String, Object>>) o;
-
- }
-
- childs.add(child);
-
- }
只需要简单说几点:
1.按照level升序,顶级节点在最前面。
2.把每一个节点的父结点,先放进map。轮到子结点的时候,把它放进父结点的children中。
3.integer比较的时候, 用queals方法,而不是==。
4.Map的key是区分类型的。
map.put(1,"a");
map.get("1");
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。