遞歸查詢單表菜單樹形結構(多級樹形結構)


/**
* 遞歸查詢樹形結構==================================================
*/
@PostMapping("/recursive")
@ResponseBody
public List<Map<String, Object>> findWorld() {
List<Map<String, Object>> allList = new ArrayList<>(); //接收所有的信息
List<Map<String, Object>> parentMapList = new ArrayList<>(); //接收獲取的父節點
List<Map<String, Object>> retList = new ArrayList<>(); //接收獲取的父節點
try {
allList = myTestService.findWorld(); //獲取所有的信息
for (int i = 0; i < allList.size(); i++) { //循環所有信息找出所有的根節點(p_id=-1)
if ("-1".equals(allList.get(i).get("p_id").toString())) {
parentMapList.add(allList.get(i)); //將找出來的根節點重新存到一個List<Map>集合中
allList.remove(i); //從所有的數據中移除根節點
i--; //每移除一個根節點就將所有數據的個數減一
}
}
retList = recursive(allList,parentMapList); //調用此方法尋找子節點
} catch (Exception e) {
e.printStackTrace();
}
return retList;
}

/**
* @param parentMapList 所有父節點
* @param allList 所有數據
* @return
*/
public List<Map<String, Object>> recursive(List<Map<String, Object>> allList,List<Map<String,Object>> parentMapList) {
//循環根節點
for(int j = 0;j<parentMapList.size();j++){
List<Map<String, Object>> tempList = new ArrayList<>(); //用來存取子節點
//循環全部節點,判斷節點中P_id是否與根節點中的id相同
for(int k = 0;k<allList.size();k++){
if(allList.get(k).get("p_id").toString().equals(parentMapList.get(j).get("id").toString())){
tempList.add(allList.get(k));
}
}
if(tempList.size()>0){
parentMapList.get(j).put("children",tempList);
recursive(allList,tempList); //此次循環又將tempList作為parentMapList(父節點去找其他的子節點),直到沒有子節點在執行j+1
}
}
return parentMapList;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM