JAVA递归实现树型结构

近期项目有个需求,需要将组织机构数据拼成树型结构返回至前端。我的做法如下:
1.由于前端展示使用的组件需要特定的属性key,所以我定义了一个VO对象,代码如下:
(本人使用了Lombok插件)

package top.yuxuange.vo;

import lombok.Data;

import java.util.List;

@Data
public class TreeVO {

    /**
     * id
     */
    private String id;

    /**
     * title
     */
    private String title;

    /**
     * 子级
     */
    private List children;
}

2.编写树型结构工具类:

这是我数据库中组织机构的根节点CODE的截图

1

package top.yuxuange.util;

import org.springframework.stereotype.Component;
import top.yuxuange.model.SysDept;
import top.yuxuange.vo.TreeVO;

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

/**
 * 获取组织机构树
 *
 * @author yuxuange
 * @Date 2021-02-03
 */
@Component
public class TreeUtil {

    /**
     * 组织机构表,根节点CODE
     */
    private static final String TREE_ROOT_CODE = "0";
	
	/**
	 * 标准版
	 */
    public static List getTree(List record) {
        List treeList = new LinkedList();
        for (SysDept sysDept : record) {
            if (TREE_ROOT_CODE.equals(sysDept.getParentId())) {
                TreeVO treeVO = new TreeVO();
                treeVO.setId(sysDept.getCode());
                treeVO.setTitle(sysDept.getName());
                treeVO.setChildren(getChild(sysDept.getCode(), record));
                treeList.add(treeVO);
            }
        }
        return treeList;
    }

    private static List getChild(String code, List record) {
        List childrenList = new LinkedList();
        for (SysDept sysDept : record) {
            if (code.equals(sysDept.getParentId())) {
                TreeVO treeVO = new TreeVO();
                treeVO.setId(sysDept.getCode());
                treeVO.setTitle(sysDept.getName());
                treeVO.setChildren(getChild(sysDept.getCode(), record));
                childrenList.add(treeVO);
            }
        }
        return childrenList;
    }
	
	/**
	 * lamda表达式版
	 */
    public static List getTreeEX(List record){
        return record.stream().filter(sysDept -> {return TREE_ROOT_CODE.equals(sysDept.getParentId());}).map(sysDept -> {
            TreeVO treeVO = new TreeVO();
            treeVO.setId(sysDept.getCode());
            treeVO.setTitle(sysDept.getName());
            treeVO.setChildren(getChildEX(sysDept.getCode(),record));
            return treeVO;
        }).collect(Collectors.toList());
    }


    private static List getChildEX(String code,List record){
        return record.stream().filter(sysDept -> {return code.equals(sysDept.getParentId());}).map(sysDept -> {
            TreeVO treeVO = new TreeVO();
            treeVO.setId(sysDept.getCode());
            treeVO.setTitle(sysDept.getName());
            treeVO.setChildren(getChildEX(sysDept.getCode(),record));
            return treeVO;
        }).collect(Collectors.toList());
    }
}

3.查询数据,调用工具类,返回结果如下:
JAVA递归实现树型结构_第1张图片

你可能感兴趣的:(Java,java)