多叉树的构建
有個需求,是一張地區表,地區表中包含多層級的地區,如:中國,河北省,邢臺市,橋東區。一共有4個層級。數據庫字段設計為
我要將這些數據轉為有層級關系的json數據:很顯然數據的結構是個樹,于是就要建立樹的結構:
1 public class Node{
2 public Map<Integer,Node> childs = new HashMap<>();
3 public String name; public Integer id;
4 public Integer parentId;
5 }
從數據庫取到所有數據 attrAreas進行一個樹的構建:
1 public void local(List<ModelAttrArea> attrAreas){ //建立根節點
2 Node root=new Node(); Map<Integer,Node> maps= new HashMap<>(); //遍歷所有節點,將節點放入節點map中
3 for(ModelAttrArea temp:attrAreas) {
4 Node node = new Node();
5 node.name = temp.getName();
6 node.id = temp.getID();
7 node.parentId = temp.getParentId();
8 maps.put(temp.getID(),node);
9 }
10
11 //開始遍歷已經放好的map,將沒有父節點的節點放倒根目錄下,把有父節點的節點,找到父節點,然后給父節點添加子節點。
12 for (Map.Entry<Integer, Node> entry : maps.entrySet()){
13 Node e=entry.getValue();
14 Integer parentId = e.parentId;
15 if(parentId==null){
16 root.childs.put(e.id, e);
17 }else{
18 Node pnode = maps.get(parentId);
19 pnode.childs.put(e.id,e);
20 }
21 }
22 }
23 }
參考地址:http://www.imooc.com/article/6909?block_id=tuijian_wz
總結
- 上一篇: 【WP】攻防世界-杂项-Misc
- 下一篇: UNIGUI