Tree construction

In the development, when encountering the data of the hierarchical relationship , it should be displayed in the form of a tree diagram. I basically can't use it on the Internet before. Record the tree structure with java code:

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
public class Tree<T> implements Serializable {
    
    
    private Integer id;
    private String typeName; // 类型名称
    private Integer parentId; // 父id
    private Integer score;  //分数
    private List<Tree<T>>  children; // 子节点
    
    public Tree(Integer id, String typeName, Integer parentId) {
    
    
        this.id = id;
        this.typeName = typeName;
        this.parentId = parentId;
    }
    public Tree() {
    
    
        super();
    }
}
import java.util.ArrayList;
import java.util.List;

public class BuildTree {
    
    
    public static <T> Tree<T> buildNodes(List<Tree<T>> nodes) {
    
    
        List<Tree<T>> topNodes = new ArrayList<>();
        if (nodes == null) {
    
    
            return null;
        }
        for (Tree<T> children : nodes) {
    
    
            Integer pid = children.getParentId();
            if (pid == null || "".equals(pid) || 0 == pid) {
    
    
                topNodes.add(children);
                continue;
            }

            for (Tree<T> parent : nodes) {
    
    
                Integer id = parent.getId();
                if (id != null && id == pid) {
    
    
                    if (parent.getChildren() == null) {
    
    
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(children);
                    continue;
                }
            }

        }
        Tree<T> root = new Tree<T>();
        if (topNodes.size() == 1) {
    
    
            root = topNodes.get(0);
        } else {
    
    
        	//如果没有顶级节点,就自己定义一个顶级节点
            root.setId(-1);
            root.setChildren(topNodes);
            root.setTypeName("审核阈值配置");
        }
        return root;
    }
}

The following is to construct the tree of the queried data:

 public HisiResult getAuditType() {
    
    
 		//自己定义一个类对象就行
        List<AuditTypeControl> auditTypeList = auditTypeControlMapper.selectAll();
        List<Tree<AuditTypeControl>> trees = new ArrayList<>();
        for (AuditTypeControl auditType : auditTypeList){
    
    
            Tree<AuditTypeControl> tree = new Tree<>();
            tree.setId(auditType.getId());
            tree.setParentId(auditType.getParentId());
            tree.setTypeName(auditType.getTypeName());
            tree.setScore(auditType.getScore());
            trees.add(tree);
        }
        Tree<AuditTypeControl> tree =  BuildTree.buildNodes(trees);
        return HisiResult.ok(tree);
    }

Guess you like

Origin blog.csdn.net/qq_32115447/article/details/106643002