使用递归生成树状结构数据

使用递归构建树结构数据

前段时间公司项目需求需要生成树状结构的数据,在这里记录一下!

entity类

在同一张表里存在parentId和id(子id),当parentId为null时表示这就是树结构的最高层

@Data
public class DanalyIndexAlgotithm{
	//主键id
	private String id
	//姓名
	private String name
	//优先级(这个项目中用到了这个字段,看情况而定,可以去掉)
	private String priority
	//父id
	private String parentId
	//子集数据
	private List<DanalyIndexAlgotithm> children;
	
}

递归

public static List<DanalyIndexAlgorithm> buildTree(List<DanalyIndexAlgotithm> nodes){
	List<DanalyIndexAlgorithm> tree = new ArrayList();
	for(DanalyIndexAlgorithm node : nodes){
		if(node.getParentId() == null){//根节点
			//根节点的顺序为0
			tree.add(node);
			node.setNum(1);
			build(node,nodes,"1");//递归
		}
	}
	return tree;
}

//递归,构建树结构
public static void build(DanalyIndexAlgorithm node, List<DanalyIndexAlgorithm>nodes, String count){
	if(!children.isEmpty){
		node.setChildren(children);
		for(DanalyIndexAlgorithm child : children){
			build(child,nodes,count);
		}
	}
}

//构建子集数据
public static List<DanalyIndexAlgorithm> getChildren(DanalyIndexAlgorithm node,List<DanalyIndexAlgorithm> nodes,String count){
	List<DanalyIndexAlgorithm> children = new ArrayList();
	for(DanalyIndexAlgorithm org : nodes){
		String pId = org.getParentId();
		if(node.getId().equals(pId)){
			org.setNum(Integer.valueOf(count) + 1 + "");
			children.add(org);
		}
	}
	return children;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值