java使用递归对树结构进行操作

1. 基础的Bean对象

数据库对象

public class Dept {


    private String id;


    private String parentId;


    private String deptName;
	
	//get set toString

}

构造数据方法

public static List<Dept> buildData() {
        
        // 构造部门数据
        Dept dept1 = new Dept("1", null, "一级部门");
        Dept dept2 = new Dept("2", "1", "二级部门");
        Dept dept3 = new Dept("3", "1", "二级部门");
        Dept dept4 = new Dept("4", "2", "三级部门");
        Dept dept5 = new Dept("5", "3", "三级部门");
        Dept dept6 = new Dept("6", "2", "三级部门");
        Dept dept7 = new Dept("7", "4", "四级部门");
        Dept dept8 = new Dept("8", "5", "四级部门");
        Dept dept9 = new Dept("9", "5", "四级部门");


        List<Dept> list = new ArrayList<>();
        list.add(dept1);
        list.add(dept2);
        list.add(dept3);
        list.add(dept4);
        list.add(dept5);
        list.add(dept6);
        list.add(dept7);
        list.add(dept8);
        list.add(dept9);


        return list;
    }

2. 获取当前节点的所有子节点,包括当前节点

	
public static void main(String[] args) {

	List<Dept> deptList = buildData();
	
	System.out.println(JSON.toJSONString(getChildList(deptList.get(1), deptList)));
	
}



/**
 * 递归向下遍历子节点信息
 *
 * @param dept 部门信息
 * @param list 部门列表
 * @return 包含该部门以及所有子部门的列表
 */
public static List<Dept> getChildList(Dept dept, List<Dept> list) {
   	String id = dept.getId();
   	// 首先把当前节点加入结果中
   	List<Dept> result = list.stream()
           .filter(val -> val.getId().equals(id)).collect(Collectors.toList());
   	// 开始递归
   	list.stream()
           .filter(item -> Objects.nonNull(item.getParentId()) && item.getParentId().equals(id))
           .forEach(item -> {
               result.addAll(getChildList(item, list));
           });
   	return result;
}

输出

[
    {
        "deptName": "二级部门",
        "id": "2",
        "parentId": "1"
    },
    {
        "deptName": "三级部门",
        "id": "4",
        "parentId": "2"
    },
    {
        "deptName": "四级部门",
        "id": "7",
        "parentId": "4"
    },
    {
        "deptName": "三级部门",
        "id": "6",
        "parentId": "2"
    }
]

3. 获取当前节点的所有父节点

public static void main(String[] args) {

   	List<Dept> deptList = buildData();
   
   	List<Dept> parentList = getParentList(deptList.get(8), deptList);

    // 根据Id去重
    parentList = parentList.stream()
            .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
                    Comparator.comparing(Dept::getId))), ArrayList::new));
    System.out.println(JSON.toJSONString(parentList));
   
}

/**
 * 获取当前节点的所有父节点
 *
 * @param dept 部门信息
 * @param list 部门列表
 * @return 该节点的所有父节点的列表
 */
public static List<Dept> getParentList(Dept dept, List<Dept> list) {

    List<Dept> result = new ArrayList<>();

    if ("0".equals(dept.getParentId())) {
        result.add(dept);
        return result;
    }
    list.stream()
            .filter(item -> Objects.nonNull(item.getParentId())
                    && item.getId().equals(dept.getParentId()))
            .forEach(item -> {
                result.add(item);
                result.addAll(getParentList(item, list));
            });
    return result;
}

输出

[
    {
        "deptName": "一级部门",
        "id": "1",
        "parentId": "0"
    },
    {
        "deptName": "二级部门",
        "id": "3",
        "parentId": "1"
    },
    {
        "deptName": "三级部门",
        "id": "5",
        "parentId": "3"
    }
]

4. 构建树结构

public static void main(String[] args) {

   	List<Dept> deptList = buildData();
   
     Dept dept = deptList.get(0);
     List<Dept> buildTree = buildTree("1", deptList);
     dept.setChildList(buildTree);

     System.out.println(JSON.toJSONString(dept));
}


/**
 * 构建树结构
 *
 * @param id   顶级部门ID,list中最顶级的父部门ID
 * @param list 部门列表
 * @return 树结构
 */
public static List<Dept> buildTree(String id, List<Dept> list) {

    List<Dept> result = new ArrayList<>();
    list.stream()
            .filter(item -> Objects.nonNull(item.getParentId()) && item.getParentId().equals(id))
            .forEach(item -> {
                List<Dept> childList = buildTree(item.getId(), list);
                if (childList.size() > 0) {
                    item.setChildList(childList);
                }
                result.add(item);
            });
    return result;
}

输出

{
    "childList": [
        {
            "childList": [
                {
                    "childList": [
                        {
                            "deptName": "四级部门",
                            "id": "7",
                            "parentId": "4"
                        }
                    ],
                    "deptName": "三级部门",
                    "id": "4",
                    "parentId": "2"
                },
                {
                    "deptName": "三级部门",
                    "id": "6",
                    "parentId": "2"
                }
            ],
            "deptName": "二级部门",
            "id": "2",
            "parentId": "1"
        },
        {
            "childList": [
                {
                    "childList": [
                        {
                            "deptName": "四级部门",
                            "id": "8",
                            "parentId": "5"
                        },
                        {
                            "deptName": "四级部门",
                            "id": "9",
                            "parentId": "5"
                        }
                    ],
                    "deptName": "三级部门",
                    "id": "5",
                    "parentId": "3"
                }
            ],
            "deptName": "二级部门",
            "id": "3",
            "parentId": "1"
        }
    ],
    "deptName": "一级部门",
    "id": "1"
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值