树形结构通用方法

public class TreeUtil2 {

    private TreeUtil2() {

    }

    public static TreeUtil2 getInstance() {

        return new TreeUtil2();
    }

    public Set> getTree(List list, Long parentId) {
        if (list.size() == 0) {
            return null;
        }

        List children = list.stream().filter(x -> ((T) x).getPid().equals(parentId)).collect(Collectors.toList());
        List successor = list.stream().filter(x -> !((T) x).getId().equals(parentId)).collect(Collectors.toList());


        Set> set = new TreeSet<>();
        for (T t : children) {

            Node node = new Node();
            node.setData(t);
            set.add(node);
            Set> tree = getTree(successor, t.getId());
            if (tree != null) {
                node.setSNodes(tree);
            }
        }
        return set;
    }

    public void getChildren(List list, List target, Long id) {

        List children = list.stream().filter(x -> id.equals(x.getPid())).collect(Collectors.toList());
        List other = list.stream().filter(x -> !id.equals(x.getPid())).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(children)) {
            return;
        }

        target.addAll(children);

        for (T group : children) {

            getChildren(other, target, group.getId());
        }
    }

    public void getChildren(Node node, List target) {

        target.add(node.getData());

        Set> sNodes = node.getSNodes();

        for (Node n : sNodes) {

            getChildren(n, target);
        }
    }

    public void getParents(List list, List target, Long currentPos) {

        Optional first = list.stream().filter(x -> ((T) x).getId().equals(currentPos)).findFirst();

        if (first.isPresent()) {
            T t = first.get();
            target.add(t);
            getParents(list, target, first.get().getPid());
        }
    }

    public boolean belong(Long child, Long ancestor, List list) {

        List target = new LinkedList<>();

        getParents(list, target, child);

        boolean b=target.stream().filter(x -> x.getId().equals(ancestor)).findFirst().isPresent();

        return b;
    }

    public boolean contains(Long ancestor, Long child, List list) {

        List target = new LinkedList<>();

        getChildren(list, target, ancestor);

        boolean b=target.stream().filter(x -> x.getId().equals(child)).findFirst().isPresent();

        return b;
    }
}

 

 

public class Node implements Comparable {
    /**
     * 存放的数据
     */
    private T data;
    /**
     * 存放的子节点引用
     */
    private Set> sNodes;

}

你可能感兴趣的:(java)