java构建树形列表(带children属性)- Stream流操作

1. 实体类

package com.xietest.demo.util.tree;

import lombok.Builder;
import lombok.Data;

import java.util.List;

@Data
@Builder
public class Menu {

    private int id;

    private String name;

    private int 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;
    }
}

2. 构建树形结构方法

package com.xietest.demo.util.tree;

import com.alibaba.fastjson.JSON;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class BuildTree {

    @Test
    public void buildTreeTest() {

        List<Menu> menus = buildData();

        // 获取父节点(menu.getParentId() == 0  实际工作中0 可以当参数传入得到相对根节点下的数据)
        // 或者取当前节点的ID 作为参数传入,得到相对根节点下的数据
        List<Menu> menuList =
                menus.stream()
                        .filter(menu -> menu.getParentId() == 0)
                        //.filter(menu -> menu.getId() == 1)
                        .map(menu -> {
                            menu.setChildList(getChildrens(menu, menus));
                            return menu;
                        })
                        .collect(Collectors.toList());

        System.out.println("-------转json输出结果-------");
        System.out.println(JSON.toJSON(menuList));

    }

    /**
     * 递归查询子节点
     * @param root  根节点
     * @param all   所有节点
     * @return      根节点信息
     */
    private List<Menu> getChildrens(Menu root, List<Menu> all) {

        List<Menu> childrens =
                        all.stream()
                                .filter(menu -> Objects.equals(menu.getParentId(), root.getId()))
                                .map(menu -> {
                                    menu.setChildList(getChildrens(menu, all));
                                    return menu;
                                })
                                .collect(Collectors.toList());

        return childrens;
    }

    public List<Menu> buildData() {
        //模拟从数据库查询出来
        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",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)
        );
        return menus;
    }
}
posted @ 2022-04-05 14:32  xiexie0812  阅读(419)  评论(0编辑  收藏  举报