一、前提
可能平常会遇到一些需求,比如构建菜单,构建树形结构,数据库一般就使用父id来表示,为了降低每次查询数据库压力,可以一次性把数据查询出来然后使用Java8中的Stream流来处理构建树形结构
二、代码
实体类Menu.java
package com.ac.hello.tree;import lombok.Builder;
import lombok.Data;import java.util.List;@Data
@Builder
public class Menu {private Integer id;private String name;private Integer parentId;private 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;}
}
递归组装树形结构
package com.ac.hello.tree;import cn.hutool.json.JSONUtil;import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;public class StreamTest {public static void main(String[] args) {// 1、模拟从数据库查询出来List<Menu> menus = 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",0),new Menu(7,"根节点2.1",6),new Menu(8,"根节点2.2",6),new Menu(9,"根节点2.1.1",7),new Menu(10,"根节点2.1.2",7),new Menu(11,"根节点3",0),new Menu(12,"根节点3.1",11));// 获取父节点List<Object> collect = menus.stream().filter(m -> m.getParentId() == 0).map((m) -> {m.setChildList(getChildrens(m, menus));return m;}).collect(Collectors.toList());System.out.println("--------------------- 转json输出结果 ------------------------");System.out.println(JSONUtil.toJsonStr(collect));}/*** @description: 递归查询子节点* @param: root 根节点* @param: all 所有节点* @return: java.util.List<com.ac.hello.tree.Menu>* @date: 2023/8/7 22:33*/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;}
}
注意:使用样例时,转换json字符串工具这里使用的是hutool工具使用时需要引入下
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.16</version>
</dependency>