提前循环一遍所有节点,将父子关系保持在map里
public String buildUserDistrictTree(Listdistricts){ //三级 Map > map=new HashMap >(); for(EypArea eypArea : districts){ if (map.get(eypArea.getParentId())!=null) { map.get(eypArea.getParentId()).add(eypArea); }else { map.put(eypArea.getParentId(), new ArrayList ()); map.get(eypArea.getParentId()).add(eypArea); } } List roots=map.get("0"); Collections.sort(roots, new Comparator (){ @Override public int compare(EypArea o1, EypArea o2) { return o1.getId().compareTo(o2.getId()); } }); String tree=scmOrganizationService.buildDistrictsTreeWithCashMap(roots, map); return tree; }public String buildDistrictsTreeWithCashMap(List rootList,Map > eypAreaMap){ Stack stack=new Stack (); JSONArray roots=JSONArray.fromObject(rootList); for (int i = 0; i < roots.size(); i++) { stack.push(roots.getJSONObject(i)); } while (!stack.isEmpty()) { JSONObject parent=stack.pop(); if (ParameterUtils.hasItem(eypAreaMap.get(parent.getString("id")))) { JSONArray jsonArray=JSONArray.fromObject(eypAreaMap.get(parent.getString("id"))); parent.put("children", jsonArray); parent.put("spread", false); jsonArray=parent.getJSONArray("children"); for (int i = 0; i < jsonArray.size(); i++) { stack.push(jsonArray.getJSONObject(i)); } } } return roots.toString(); }