后端返回树结构

出参结构

java 复制代码
@Getter
@Setter
public class TreeResponse implements Serializable {
    // 主键
    private Long id;
    // 父级节点
    private Long parentId;
    // 层级
    private Byte layer;
    // 编码
    private String docCode;
    // 名称
    private String docName;
    // 子节点
    private List<TreeResponse> childNode;
}

方案一:生撸

java 复制代码
public Result<List<TreeResponse>> listTreeData(String code) {
    // 查询全量数据
    List<TreeResponse> tempTreeResponse = new ArrayList<>();
    // 树节点转换
    return Result.success(convertTreeStructure(tempTreeResponse));
}

/**
 * 树形转换
 *
 * @param tempTreeResponse 档案信息
 * @return 档案信息-树
 */
private List<TreeResponse> convertTreeStructure(List<TreeResponse> tempTreeResponse) {
    // 获取第一层级
	List<TreeResponse> treeResponse = tempTreeResponse.stream()
			.filter(value -> Objects.isNull(value.getParentId()))
			.collect(Collectors.toList());
    // 获取非第一层级数据,并以父级ID进行分组
	Map<Long, List<TreeResponse>> notFirstLayerData = tempTreeResponse.stream()
			.filter(value -> Objects.nonNull(value.getParentId()))
			.collect(Collectors.groupingBy(TreeResponse::getParentId));
	treeResponse.forEach(data -> setChildData(data, notFirstLayerData));
	return treeResponse;
}

/**
 * 设置子节点
 *
 * @param parentInfo        父节点信息
 * @param notFirstLayerData 非首节点信息
 */
private void setChildData(TreeResponse parentInfo, Map<Long, List<TreeResponse>> notFirstLayerData) {
	List<TreeResponse> childData = notFirstLayerData.get(parentInfo.getId());
	if (CollectionUtils.isNotEmpty(childData)) {
		parentInfo.setChildNode(childData);
		childData.forEach(data -> setChildData(data, notFirstLayerData));
	}
}

方案二:Hutool

java 复制代码
//配置
TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
// 自定义属性名 都要默认值的
treeNodeConfig.setWeightKey("order");
treeNodeConfig.setIdKey("rid");
// 最大递归深度
treeNodeConfig.setDeep(3);

//转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
List<Tree<String>> treeNodes = TreeUtil.<TreeNode, String>build(nodeList, "0", treeNodeConfig,
		(treeNode, tree) -> {
			tree.setId(treeNode.getId());
			tree.setParentId(treeNode.getParentId());
			tree.setWeight(treeNode.getWeight());
			tree.setName(treeNode.getName());
			// 扩展属性 ...
			tree.putExtra("extraField", 666);
			tree.putExtra("other", new Object());
		});
相关推荐
阿巴~阿巴~5 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
重生之我是Java开发战士10 小时前
【数据结构】深入理解单链表与通讯录项目实现
数据结构·链表
pusue_the_sun1 天前
数据结构——顺序表&&单链表oj详解
c语言·数据结构·算法·链表·顺序表
闪电麦坤952 天前
数据结构:用链表实现队列(Implementing Queue Using List)
数据结构·链表·队列
热爱生活的猴子2 天前
算法148. 排序链表
数据结构·算法·链表
屁股割了还要学4 天前
【数据结构入门】堆
c语言·开发语言·数据结构·c++·考研·算法·链表
·白小白5 天前
【数据结构】——顺序表链表(超详细解析!!!)
数据结构·链表
茴香豆的茴15 天前
转码刷 LeetCode 笔记[2]:203. 移除链表元素(python)
笔记·leetcode·链表
快去睡觉~5 天前
力扣109:有序链表转换二叉搜索树
算法·leetcode·链表
没有bug.的程序员6 天前
《常见高频算法题 Java 解法实战精讲(1):链表与数组》
java·算法·链表·数组