java8递归遍历树形结构
- 菜单实体类
@Data
public class Menu {
private String id;
private String name;
private String pid;
private List<Menu> children;
public Menu() {}
public Menu(String id, String name, String pid) {
this.id = id;
this.name = name;
this.pid= pid;
}
}
- 递归遍历树形结构(含有多个根节点)
public void getTreeMenu() {
List<Menu> menus = Arrays.asList(
new Menu(1, "根节点", 0),
new Menu(2, "子节点1", 1),
new Menu(3, "子子节点1.1", 2),
new Menu(6, "子子子节点1.1.1", 3),
new Menu(4, "子节点2", 1),
new Menu(5, "子子节点2.1", 4),
new Menu(6, "根节点2", 0),
new Menu(7, "子节点1", 6),
new Menu(8, "子子节点1.1", 7),
);
List<Menu> list = menus.stream().filter(menu -> "0".equals(menu.getPid())).peek(
menu -> menu.setChildren(getChildrenList(menu, menus))
).collect(Collectors.toList());
}
private List<Menu> getChildrenList(Menu root, List<Menu> menus) {
List<Menu> list = menus.stream().filter(menu ->
Objects.equals(menu.getPid(), root.getId())).map(menu -> {
menu.setChildren(this.getChildrenList(menu, menus));
return menu;
}).collect(Collectors.toList());
return list;
}
- 递归遍历树形结构(单个根节点)
public void getTreeMenu() {
List<Menu> menus = Arrays.asList(
new Menu(1, "根节点", 0),
new Menu(2, "子节点1", 1),
new Menu(3, "子子节点1.1", 2),
new Menu(6, "子子子节点1.1.1", 3),
new Menu(4, "子节点2", 1),
new Menu(5, "子子节点2.1", 4)
);
List<Menu> list = menus.stream().filter(menu -> "0".equals(menu.getPid())).peek(
menu -> menu.setChildren(getChildrenList(menu, menus))
).findFirst().orElse(new Menu());
}
private List<Menu> getChildrenList(Menu root, List<Menu> menus) {
List<Menu> list = menus.stream().filter(menu ->
Objects.equals(menu.getPid(), root.getId())).map(menu -> {
menu.setChildren(this.getChildrenList(menu, menus));
return menu;
}).collect(Collectors.toList());
return list;
}
- 递归删除节点及其子节点(结合MybatisPlus框架)
public void deleteMenus(String id) {
List<String> idList = new ArrayList<>();
this.selectChildListById(id, idList);
idList.add(id);
baseMapper.deleteBatchIds(idList);
}
private String selectChildListById(String id, List<String> idList) {
List<Menu> childList = baseMapper.selectList(new QueryWrapper<Menu>().eq("pid", id).select("id"));
childList.forEach(menu-> {
idList.add(menu.getId());
this.selectChildListById(menu.getId(), idList);
});
}