java树结构工具类
非ban必选 人气:6菜单实体类
package com.example.demo.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @Builder @AllArgsConstructor @NoArgsConstructor 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; } }
生成树结构工具类
package com.example.demo.util; import cn.hutool.json.JSONUtil; import com.example.demo.entity.Menu; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class TreeUtil { /** * 递归查询子节点 * * @param root 根节点 * @param all 所有节点 * @return 根节点信息 */ public 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; } * @param parentId 父节点id * @param menus 菜单集合 * @return 返回id等于parentId的子孙节点树结构 (不包含id等于parentId的节点) public static List<Menu> getTree(Integer parentId, List<Menu> menus) { //获取父节点 List<Menu> tree = menus.stream().filter(m -> Objects.equals(parentId,m.getParentId())).map( m.setChildList(getChildrens(m, menus)); return tree; public static void main(String... args) { //模拟从数据库查询出来 List<Menu> menus = Arrays.asList( new Menu(1, "0-1", 0), new Menu(2, "0-1-2", 1), new Menu(3, "0-1-2-3", 2), new Menu(4, "0-1-2-4", 2), new Menu(5, "0-1-2-5", 2), new Menu(6, "0-6", 0), new Menu(7, "0-6-7", 6), new Menu(8, "0-6-8", 6), new Menu(9, "0-6-7-9", 7), new Menu(10, "0-6-7-10", 7), new Menu(11, "0-11", 0), new Menu(12, "0-11-12", 11) ); List<Menu> tree = getTree(1,menus); System.out.println("-------转json输出结果-------"); System.out.println(JSONUtil.parseArray(tree).toString()); }
加载全部内容