首先是实体类
java">public class DwdCusPtlSelectDto {
//id
private String key;
//值
private String value;
//中文名
private String title;
private List<DwdCusPtlSelectDto> children;
private String parentId;
public void addChild(DwdCusPtlSelectDto child) {
if(this.children == null){
this.children = new LinkedList<>();
}
this.children.add(child);
}
}
方法
java">private List<DwdCusPtlSelectDto> rulesToTree(List<DwdCusPtlSelectDto> assetRules) {
List<DwdCusPtlSelectDto> list = new LinkedList<>();
Map<String, DwdCusPtlSelectDto> nodeMap = new HashMap<>();
// 将所有节点放入Map中,方便后续查找
for (DwdCusPtlSelectDto node : assetRules) {
nodeMap.put(node.getKey(), node);
}
//不知道为啥概率性出现重复结点,没办法就拿set判断下
Set<String> set = new HashSet<>();
// 构建树结构
for (DwdCusPtlSelectDto node : assetRules) {
if ("all".equals(node.getParentId())) {
list.add(node);
// 找到根节点
} else {
DwdCusPtlSelectDto parentNode = nodeMap.get(node.getParentId());
if (parentNode != null&&!set.contains(node.getKey())) {
parentNode.addChild(node);
set.add(node.getKey());
}
}
}
return list;
}
如果有老哥知道为啥会概率醒出现重复结点问题,可以评论告诉我一下