比如从数据库里读取出的用户菜单是平级的list类型,需要返回给前端的是tree结构 ,这时用我这个方法可以快速实现这个转换:
先写一个节点父类,其它要转换的类可以继承它,让这个方法更通用。
package com.gnetek.monitor.core.node;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.List;
/**
* @Description 带id 和 parentId 的树型结构
* @Author Darren Huang
* @Date 2024-03-15 9:05
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "BaseNode", description = "带id和parentId的树型结构的类")
public class BaseNode<PK extends Serializable> implements Serializable {
private static final long serialVersionUID = 3526233231056646449L;
/**
* 主键ID
*/
@ApiModelProperty(value = "主键ID")
protected PK id;
/**
* 父节点ID
*/
@ApiModelProperty(value = "父节点ID")
protected PK parentId;
/**
* 层级
*/
@ApiModelProperty(value = "层级")
protected Integer type;
/**
* 子节点集合
*/
@ApiModelProperty(value = "子节点集合")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
protected List<? extends BaseNode<PK>> children;
/**
* 设置节点值, 这个是用于如果子类的主键父主键和层级与这里定义的名字不一样时,可以另外赋值
*
* @param id id
* @param parentId 父id
* @param type 层级
*/
public void setNodeFields(PK id, PK parentId, Integer type) {
this.id = id;
this.parentId = parentId;
this.type = type;
}
}
实现转换的工具类:
package com.gnetek.monitor.core.node;
import cn.hutool.core.collection.CollectionUtil;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @Description 合并节点类型
* @Author Darren Huang
* @Date 2024-03-15 9:14
*/
public class NodeMergerUtil {
/**
* list转成树, 没有type值时,注意如果子节点与父节点的id可能相同不能用,会有问题
*
* @param treeList 树列表
* @param parentId 父id
* @return {@link List}<{@link T}>
*/
public static <T extends BaseNode<PK>, PK extends Serializable> List<T> streamToTree(List<T> treeList, PK parentId) {
if (CollectionUtil.isEmpty(treeList)) {
return null;
} else {
return treeList.stream()
// 过滤父节点
.filter(parent -> Objects.equals(parent.getParentId(), parentId))
// 把父节点children递归赋值成为子节点
.peek(child -> {
List<T> childTreeList = treeList.stream()
.filter(node -> !node.equals(child) || !Objects.equals(node.getType(), child.getType()))
.collect(Collectors.toList());
child.setChildren(streamToTree(childTreeList, child.getId()));
}).collect(Collectors.toList());
}
}
}