java递归树结构

java递归树结构

代码

package com.example.demo.util;

import lombok.Data;

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

@Data
public class TreeMenu {

    private Integer id;

    private String label;

    private Integer parentId;

    private List<TreeMenu> childNode;

    /**
     * 获取树结构
     *
     * @param record
     * @param rootNode
     * @return
     */
    public static List<? extends TreeMenu> buildTree(List<? extends TreeMenu> record, Integer rootNode) {
        return record.stream().filter(t -> rootNode.equals(t.getParentId())).map(t -> {
            t.setChildNode((List<TreeMenu>) getChildNode(t.getId(), record));
            return t;
        }).collect(Collectors.toList());
    }

    /**
     * 获取子节点
     *
     * @param code
     * @param record
     * @return
     */
    private static List<? extends TreeMenu> getChildNode(Integer code, List<? extends TreeMenu> record) {
        return record.stream().filter(t -> code.equals(t.getParentId())).map(t -> {
            t.setChildNode((List<TreeMenu>) getChildNode(t.getId(), record));
            return t;
        }).collect(Collectors.toList());
    }

}

你可能感兴趣的:(工具类,java,开发语言)