java简单递归实现树形
在开发过程中微信小程序树形控件需要按照规定格式返回数据,于是简单编写了一个递归循环
@Override
public List<Map<String, Object>> getAppTreeData(Integer consId, String structType) {
Map<String,Object> params = new HashMap<String,Object>();// 传入参数
params.put("consId", consId);
params.put("type", structType);
List<Map<String, Object>> list = new ArrayList<>();// 自己方法接入参数
List<Map<String,Object>> rList = new ArrayList<>();// 格式接受参数的集合
for (Map<String, Object> map : list) {// 循环
Map<String,Object> aMap = new HashMap<String,Object>();
String parentSturctId = String.valueOf(map.get("parentSturctId"));
String structDetId = String.valueOf(map.get("structDetId"));
if (parentSturctId.equals("0")) {// 先判断顶级节点
aMap.put("id", map.get("msId"));// 存入要求数据
aMap.put("name", map.get("unitName"));// 存入要求数据
List<Map<String,Object>> clist = queryChildren(structDetId,list);// 递归节点的下级数据
aMap.put("children", clist);
rList.add(aMap);
}
}
return rList;
}
public List<Map<String,Object>> queryChildren(String structDetId, List<Map<String, Object>> list){
List<Map<String,Object>> rList= new ArrayList<>();
for (Map<String, Object> map : list) {
Map<String,Object> aMap = new HashMap<String,Object>();
String parentSturctId = String.valueOf(map.get("parentSturctId"));
String meStructDetId = String.valueOf(map.get("structDetId"));
if (structDetId.equals(parentSturctId)) {// 子节点循环,若是没有下级节点将不再调用
aMap.put("id", map.get("msId"));
aMap.put("name", map.get("unitName"));
List<Map<String,Object>> clist = queryChildren(meStructDetId,list);
aMap.put("children", clist);
rList.add(aMap);
}
}
return rList;
}