TreeUtils:
package com.ruoyi.common.core.utils.GuavaUtils.TreeUtils;
import com.alibaba.fastjson.JSON;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @ProjectName: trunk
* @Package: com.ruoyi.common.core.utils.GuavaUtils.TreeUtils
* @ClassName: TreeUtils
* @Author: lgn
* @Description:
* @Date: 2022/4/18 17:45
* @Version: 1.0
*/
public class TreeUtils {
/**
* @Method getMenu
* @Author lgn
* @Version 1.0
* @Description 组装树形菜单
* @Return
* @Exception
* @Date 2022/4/18
*/
private static List<Menu> getMenu(List<Menu> menusList) {
//组装树形菜单
List<Menu> collectList = menusList.stream().filter(m -> m.getParentId() == 0).map(
(m) -> {
m.setChildList(getChildrens(m, menusList));
return m;
}
).collect(Collectors.toList());//Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到List、Set、Map)。
return collectList;
}
/**
* 递归查询子节点
* @param root 根节点
* @param all 所有节点
* @return 根节点信息
*/
private static List<Menu> getChildrens(Menu root, List<Menu> all) {
List<Menu> children = all.stream().filter(m -> {
return Objects.equals(m.getParentId(), root.getId());
}).map(
(m) -> {
m.setChildList(getChildrens(m, all));
return m;
}
).collect(Collectors.toList());
return children;
}
public static void main(String[] args) {
List<Menu> menusList = Arrays.asList(
new Menu(1,"根节点",0),
new Menu(2,"子节点1",1),
new Menu(3,"子节点1.1",2),
new Menu(4,"子节点1.2",2),
new Menu(5,"根节点1.3",2),
new Menu(6,"根节点2",1),
new Menu(7,"根节点2.1",6),
new Menu(8,"根节点2.2",6),
new Menu(9,"根节点2.2.1",7),
new Menu(10,"根节点2.2.2",7),
new Menu(11,"根节点3",1),
new Menu(12,"根节点3.1",11)
);
List<Menu> collectList= getMenu(menusList);
String jsonOutput= JSON.toJSONString(collectList);
System.out.println("转json输出结果:"+jsonOutput);
}
}
Menu VO类
package com.ruoyi.common.core.utils.GuavaUtils.TreeUtils;
import lombok.Builder;
import lombok.Data;
import java.util.List;
/**
* @ProjectName: trunk
* @Package: com.ruoyi.common.core.utils.GuavaUtils.TreeUtils
* @ClassName: Menu
* @Author: lgn
* @Description: 菜单类
* @Date: 2022/4/18 17:43
* @Version: 1.0
*/
@Data
@Builder
public class Menu {
/**
* id
*/
public Integer id;
/**
* 名称
*/
public String name;
/**
* 父id ,根节点为0
*/
public Integer parentId;
/**
* 子节点信息
*/
public List<Menu> childList;
public Menu(Integer id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
public Menu(Integer id, String name, Integer parentId, List<Menu> childList) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.childList = childList;
}
}