在平时的业务中,避免不了使用递归,比如菜单列表,区域列表等,数据库一般就使用父id来表示,为了降低数据库的查询压力,我们可以使用Java8中的Stream流一次性把数据查出来,然后通过流式处理。
下来用代码做个测试
@Data
public class Area {
/**
* id
*/
public Integer id;
/**
* 名称
*/
public String areaName;
/**
* 父id,根节点为0
*/
public Integer parentId;
/**
* 子节点信息
*/
public List<Area> childList;
public Area(Integer id, String areaName, Integer parentId) {
this.id = id;
this.areaName = areaName;
this.parentId = parentId;
}
public Area(Integer id, String areaName, Integer parentId, List<Area> childList) {
this.id = id;
this.areaName = areaName;
this.parentId = parentId;
this.childList = childList;
}
}
public class TestTree {
//模拟从数据库查询出来
List<Area> areas = Arrays.asList(
new Area(1,"根节点",0),
new Area(2,"陕西省",1),
new Area(3,"西安市",2),
new Area(4,"延安市",2),
new Area(5,"雁塔区",3),
new Area(6,"四川省",1),
new Area(7,"成都市",6),
new Area(8,"青牛区",7),
new Area(9,"绵阳市",6)
);
//获取父节点
List<Area> collect = areas.stream().filter(m -> m.getParentId() == 0).map(
(m) -> {
m.setChildList(getChildrens(m, areas));
return m;
}
).collect(Collectors.toList());
/**
* 递归查询子节点
* @param root 根节点
* @param areaList 所有节点
* @return 根节点信息
*/
private List<Area> getChildrens(Area root, List<Area> areaList) {
return areaList.stream().filter(m -> {
return Objects.equals(m.getParentId(), root.getId());
}).map(
(m) -> {
m.setChildList(getChildrens(m, areaList));
return m;
}
).collect(Collectors.toList());
}
@org.junit.Test
public void test(){
System.out.println("-------转json输出结果-------");
System.out.println(JSON.toJSON(collect));
}
}
?大家可以进来一起探讨问题。
?