原始數據以下java
[ { "name":"甘肅省", "pid":0, "id":1 }, { "name":"天水市", "pid":1, "id":2 }, { "name":"秦州區", "pid":2, "id":3 }, { "name":"北京市", "pid":0, "id":4 }, { "name":"昌平區", "pid":4, "id":5 } ]
現須要是使用java將以上數據轉爲樹形結構,轉化後下的結構以下json
[ { "children":[ { "children":[ { "name":"秦州區", "pid":2, "id":3 } ], "name":"天水市", "pid":1, "id":2 } ], "name":"甘肅省", "pid":0, "id":1 }, { "children":[ { "name":"昌平區", "pid":4, "id":5 } ], "name":"北京市", "pid":0, "id":4 } ]
代碼以下數組
/** - listToTree - <p>方法說明<p> - 將JSONArray數組轉爲樹狀結構 - @param arr 須要轉化的數據 - @param id 數據惟一的標識鍵值 - @param pid 父id惟一標識鍵值 - @param child 子節點鍵值 - @return JSONArray */ public static JSONArray listToTree(JSONArray arr,String id,String pid,String child){ JSONArray r = new JSONArray(); JSONObject hash = new JSONObject(); //將數組轉爲Object的形式,key爲數組中的id for(int i=0;i<arr.size();i++){ JSONObject json = (JSONObject) arr.get(i); hash.put(json.getString(id), json); } //遍歷結果集 for(int j=0;j<arr.size();j++){ //單條記錄 JSONObject aVal = (JSONObject) arr.get(j); //在hash中取出key爲單條記錄中pid的值 JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString()); //若是記錄的pid存在,則說明它有父節點,將她添加到孩子節點的集合中 if(hashVP!=null){ //檢查是否有child屬性 if(hashVP.get(child)!=null){ JSONArray ch = (JSONArray) hashVP.get(child); ch.add(aVal); hashVP.put(child, ch); }else{ JSONArray ch = new JSONArray(); ch.add(aVal); hashVP.put(child, ch); } }else{ r.add(aVal); } } return r; } 測試代碼以下 public static void main(String[] args){ List<Map<String,Object>> data = new ArrayList<>(); Map<String,Object> map = new HashMap<>(); map.put("id",1); map.put("pid",0); map.put("name","甘肅省"); data.add(map); Map<String,Object> map2 = new HashMap<>(); map2.put("id",2); map2.put("pid",1); map2.put("name","天水市"); data.add(map2); Map<String,Object> map3 = new HashMap<>(); map3.put("id",3); map3.put("pid",2); map3.put("name","秦州區"); data.add(map3); Map<String,Object> map4 = new HashMap<>(); map4.put("id",4); map4.put("pid",0); map4.put("name","北京市"); data.add(map4); Map<String,Object> map5 = new HashMap<>(); map5.put("id",5); map5.put("pid",4); map5.put("name","昌平區"); data.add(map5); System.out.println(JSON.toJSONString(data)); JSONArray result = listToTree(JSONArray.parseArray(JSON.toJSONString(data)),"id","pid","children"); System.out.println(JSON.toJSONString(result)); }
我在網上找了不少方法,本身寫的這個思路清晰,代碼量少,但願能找到志同道合的朋友,看看還有沒有優化的地方。測試
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class ZhField { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String id; /** * 上級領域id */ @Column(name = "parent_id") private String parentId; /** * 領域名稱 */ private String name; /** * 排序 */ private Integer sort; }
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.List; import java.util.Map; @Data @AllArgsConstructor @NoArgsConstructor public class TreeMenuNode implements Serializable { private String id; private String parentId; private String name; private Integer sort; private List<TreeMenuNode> children; private Boolean isAble; /**20180929zhw添加 樹的額外屬性(至少含有父節點ID:"parentId")**/ private Map<String,Object> attributes; }
package com.egaoqi.service.impl.company; import com.egaoqi.entity.ZhField; import com.egaoqi.util.TreeMenuNode; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author zhizhao * @description * @create 2018-11-14 9:07 */ public class toModel { private static void forEach(Map<String, List<TreeMenuNode>> collect, TreeMenuNode treeMenuNode) { List<TreeMenuNode> treeMenuNodes = collect.get(treeMenuNode.getId()); if(collect.get(treeMenuNode.getId())!=null){ //排序 treeMenuNodes.sort((u1, u2) -> u1.getSort().compareTo(u2.getSort())); treeMenuNodes.stream().sorted(Comparator.comparing(TreeMenuNode::getSort)).collect(Collectors.toList()); treeMenuNode.setChildren(treeMenuNodes); treeMenuNode.getChildren().forEach(t->{ forEach(collect,t); }); } } public static void main(String[] args) { List<ZhField> zhFields = new ArrayList<>(); List<TreeMenuNode> treeNodeList = new ArrayList<>(); //轉換數據,這個是前端須要的格式。 zhFields.forEach(t->{ TreeMenuNode treeMenuNode = new TreeMenuNode(); treeMenuNode.setId(t.getId()); treeMenuNode.setParentId(t.getParentId()); treeMenuNode.setName(t.getName()); treeMenuNode.setSort(t.getSort()); treeNodeList.add(treeMenuNode); }); //分組 Map<String, List<TreeMenuNode>> collect = treeNodeList.stream().collect(Collectors.groupingBy(TreeMenuNode::getParentId)); //樹形結構 確定有一個根部,個人這個根部的就是parentId.euqal("0"),並且只有一個就get("0") TreeMenuNode treeMenuNode = collect.get("0").get(0); //拼接數據 forEach(collect, treeMenuNode); } }