java 递归使用范例
javaBean
package cn.webname.test;
import java.util.List;
public class RegionBeanTree {
private int id;
private String code;
private String lable;
private String pid;
private List<RegionBeanTree> children;
// 省略构造方法,get/set方法,toString方法
}
测试代码
package cn.webname.test;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class treeController {
private List<RegionBeanTree> rootList; // 根节点对象存放到这里
private List<RegionBeanTree> bodyList; // 其他节点存放到这里,可以包含根节点
public treeController(List<RegionBeanTree> rootList, List<RegionBeanTree> bodyList) {
this.rootList = rootList;
this.bodyList = bodyList;
}
public List<RegionBeanTree> getTree() { // 调用的方法入口
if (bodyList != null && !bodyList.isEmpty()) {
// 声明一个map,用来过滤已操作过的数据
Map<String, String> map = Maps.newHashMapWithExpectedSize(bodyList.size());
rootList.forEach(beanTree -> getChild(beanTree, map));
return rootList;
}
return null;
}
public void getChild(RegionBeanTree beanTree, Map<String, String> map) {
List<RegionBeanTree> childList = Lists.newArrayList();
bodyList.stream().filter(c -> !map.containsKey(c.getCode())).filter(c -> c.getPid().equals(beanTree.getCode()))
.forEach(c -> {
map.put(c.getCode(), c.getPid());
getChild(c, map);
childList.add(c);
});
beanTree.setChildren(childList);
}
public static void main(String[] args) {
RegionBeanTree beanTree1 = new RegionBeanTree();
beanTree1.setCode("540000");
beanTree1.setLable("西藏省");
beanTree1.setPid("100000"); // 最高节点
RegionBeanTree beanTree2 = new RegionBeanTree();
beanTree2.setCode("540100");
beanTree2.setLable("拉萨市");
beanTree2.setPid("540000");
RegionBeanTree beanTree3 = new RegionBeanTree();
beanTree3.setCode("540300");
beanTree3.setLable("昌都市");
beanTree3.setPid("540000");
RegionBeanTree beanTree4 = new RegionBeanTree();
beanTree4.setCode("540121");
beanTree4.setLable("林周县");
beanTree4.setPid("540100");
RegionBeanTree beanTree5 = new RegionBeanTree();
beanTree5.setCode("540121206");
beanTree5.setLable("阿朗乡");
beanTree5.setPid("540121");
RegionBeanTree beanTree6 = new RegionBeanTree();
List<RegionBeanTree> rootList = new ArrayList<>();
rootList.add(beanTree1);
List<RegionBeanTree> bodyList = new ArrayList<>();
bodyList.add(beanTree1);
bodyList.add(beanTree2);
bodyList.add(beanTree3);
bodyList.add(beanTree4);
bodyList.add(beanTree5);
treeController utils = new treeController(rootList, bodyList);
List<RegionBeanTree> result = utils.getTree();
System.out.println(JSONObject.toJSON(result));
}
}
结果展示
[
{
"lable":"西藏省",
"pid":"100000",
"code":"540000",
"id":0,
"children":[
{
"lable":"拉萨市",
"pid":"540000",
"code":"540100",
"id":0,
"children":[
{
"lable":"林周县",
"pid":"540100",
"code":"540121",
"id":0,
"children":[
{
"lable":"阿朗乡",
"pid":"540121",
"code":"540121206",
"id":0,
"children":[
]
}
]
}
]
},
{
"lable":"昌都市",
"pid":"540000",
"code":"540300",
"id":0,
"children":[
]
}
]
}
]