java树形结构数据搜索

    public static List search(List data, String text) {
        List res = new ArrayList<>();
        for (TreeNode treeNode : data) {
            List children = treeNode.getChildren();
            if (children != null && children.size() > 0) {
                List searchData = search(children, text);
                TreeNode tn = new TreeNode();
                tn.setId(treeNode.getId());
                tn.setTitle(treeNode.getTitle());
                tn.setDescription(treeNode.getDescription());
                tn.setChildren(searchData);

                if (tn.getTitle().contains(text) || searchData.size() > 0) {
                    res.add(tn);
                }
            } else {
                if (treeNode.getTitle().contains(text)) {
                    res.add(treeNode);
                }
            }
        }
        return res;
    }

 

 

public class TreeNode {

    private Integer id;
    private String title;
    private String description;
    private List children;

    public TreeNode() {
    }

    public TreeNode(Integer id, String title, String description) {
        this.id = id;
        this.title = title;
        this.description = description;
    }

    public TreeNode(Integer id, String title, String description, List children) {
        this.id = id;
        this.title = title;
        this.description = description;
        this.children = children;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List getChildren() {
        return children;
    }

    public void setChildren(List children) {
        this.children = children;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", description='" + description + '\'' +
                ", children=" + children +
                '}';
    }
}

 

你可能感兴趣的:(JAVA,树的搜索)