本文主要是介绍后端返回树结构,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
出参结构
@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;
}
方案一:生撸
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
//配置
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());});
这篇关于后端返回树结构的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!