2024年3月17日
数据库保存的对象均为单个对象。返回前端为tree展示。
之前见过全部轮询,但是由于轮询过多导致在一万多条数据耗时较久。现在改进为先进行分组,然后再进行轮询查找对应孩子对象list。用以提高效率
huool和json可以按需引入。不影响核心功能
直接将代码展示
import java.util.List;
public class TreeNode {
private Long id;
private String label;
private Long parentId;
private List<TreeNode> children;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public List<TreeNode> getChildren() {
return children;
}
public void setChildren(List<TreeNode> children) {
this.children = children;
}
}
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TreeNodeUtil {
public static void main(String[] args) {
List<TreeNode> allList=new LinkedList<>();
for (int i = 0; i < 20; i++) {
TreeNode treeNode=new TreeNode();
treeNode.setId(i+1L);
treeNode.setLabel("label"+i);
if (i<3){
treeNode.setParentId(0L);
}else if (i<8){
treeNode.setParentId(1L);
}else if (i<12){
treeNode.setParentId(2L);
}else if (i<15){
treeNode.setParentId(5L);
}else {
treeNode.setParentId(6L);
}
allList.add(treeNode);
}
List<TreeNode> treeNodes = listToTree(allList, 0L);
System.out.println("json-> " + JSONObject.toJSONString(treeNodes));
}
public static List<TreeNode> listToTree(List<TreeNode> allList, Long rootId) {
Map<Long, List<TreeNode>> treeMap = allList.stream().filter(treeNode -> treeNode.getParentId()!=null).collect(Collectors.groupingBy(TreeNode::getParentId));
if(treeMap==null){
return new LinkedList<>();
}
List<TreeNode> treeNodes = treeMap.get(rootId);
if (treeNodes!=null){
treeNodes.sort(Comparator.comparingLong(o -> Convert.toLong(o.getId(), 0L)));
findChildren(treeMap,treeNodes);
}else {
treeNodes=new LinkedList<>();
}
return treeNodes;
}
// 递归获取全部childen列表
private static void findChildren(Map<Long, List<TreeNode>> treeMap, List<TreeNode> treeNodes) {
for (TreeNode treeNode : treeNodes) {
Long id = treeNode.getId();
List<TreeNode> treeNodes1 = treeMap.get(id);
if (treeNodes1!=null){
treeNodes1.sort(Comparator.comparingLong(o -> Convert.toLong(o.getId(), 0L)));
treeNode.setChildren(treeNodes1);
findChildren(treeMap,treeNodes1);
}else {
treeNode.setChildren(new LinkedList<>());
}
}
}
}