提供一个构建树结构的类,支持同级别排序

需要组装成树的返回实体需要实现该类

public interface TreeStructure<T, S extends TreeStructure> extends Comparable<S>{

    //获取父节点id
    T getParentId();

    //获取当前节点id
    T getId();

    //获取子级集合
    Collection<S> getChildren();

    //设置子级集合
    void setChildren(Collection<S> children);

    /**
     * 需要排序则覆写该方法,返回拿来排序的字段
     */
    default Integer getSortIndex(){
        return 0;
    }

    @Override
    default int compareTo(S o) {
        if(o == null){
            return -1;
        }
        if(this.getSortIndex() == null && o.getSortIndex() == null){
            if(getId() instanceof Long && o.getId() instanceof Long){
                return ((Long) getId()).longValue() < ((Long) o.getId()).longValue() ? -1 : 1;
            }
            return 0;
        }
        if(this.getSortIndex() == null){
            return -1;
        }
        if(o.getSortIndex() == null){
            return 1;
        }
        if(this.getSortIndex().intValue() == o.getSortIndex().intValue()){
            if(getId() instanceof Long && o.getId() instanceof Long){
                return ((Long) getId()).longValue() < ((Long) o.getId()).longValue() ? -1 : 1;
            }
            return 0;
        }
        return this.getSortIndex().intValue() < o.getSortIndex().intValue() ? -1 : 1;
    }

    /**
     * 返回parentId为rootId的树级列表(返回的treeList中的每个节点的parentId是统一的rootId)
     * T:构建父子层级的类型依据
     * S:叶子节点
     */
    static <T, S extends TreeStructure<T, S>> List<S> buildTreeList(List<S> list, T rootId) {
        if(CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        Map<T, S> map = list.stream().collect(Collectors.toMap(TreeStructure::getId, Function.identity(), (k1, k2) -> k1));
        List<S> sortedList = list.stream().sorted().collect(Collectors.toList());
        List<S> treeList = new LinkedList<>();
        for(S t  : sortedList){
            T parentId = t.getParentId();
            if(map.containsKey(parentId)){
                S parent = map.get(parentId);
                Collection<S> children = parent.getChildren();
                if(children == null){
                    children = new LinkedList<>();
                    parent.setChildren(children);
                }
                children.add(t);
            }
            if(parentId != null && parentId.equals(rootId)){
                treeList.add(t);
            }
        }
        map.clear();
        return treeList;
    }

    /**
     * 返回自构建的树级列表(返回的treeList中的每个节点的parentId很可能不一样)
     * T:构建父子层级的类型依据
     * S:叶子节点
     */
    static <T, S extends TreeStructure<T, S>> List<S> buildTreeList(List<S> list) {
        if(CollectionUtils.isEmpty(list)){
            return Collections.emptyList();
        }
        Map<T, S> map = list.stream().collect(Collectors.toMap(TreeStructure::getId, Function.identity(), (k1, k2) -> k1));
        List<S> sortedList = list.stream().sorted().collect(Collectors.toList());
        sortedList.removeIf(t -> {
            T parentId = t.getParentId();
            if(map.containsKey(parentId)){
                S parent = map.get(parentId);
                Collection<S> children = parent.getChildren();
                if(children == null){
                    children = new LinkedList<>();
                    parent.setChildren(children);
                }
                children.add(t);
                return true;
            }
            return false;
        });
        map.clear();
        return sortedList;
    }

    /**
     * 返回以root为根结点构建树级结构
     */
    static <S extends TreeStructure> S buildRootTree(List<S> list, S root){
        root.setChildren(buildTreeList(list, root.getId()));
        return root;
    }

    /**
     * 返回以root为根结点构建树级结构
     */
    static <S extends TreeStructure<T,S>, T> S buildTree(List<S> list, T rootId){
        S root = list.stream().filter(item -> item.getId().equals(rootId)).findAny()
                .orElseThrow(() -> BusinessException.create(SystemErrorCode.INTERNAL_SERVER_ERROR));
        root.setChildren(buildTreeList(list, root.getId()));
        return root;
    }

    /**
     *  筛选保留符合条件的树级列表:
     *  <h3>保留符合条件的元素,以及其直接父元素和其子级元素</h3>
     *  <p>1.遍历入参中每一个元素S,若predicate.test(S)==true则保留该元素及其所有子级元素</p>
     *  <p>2.若predicate.test(S)==false则递归遍历S的子级元素</p>
     *
     * @param treeCollection 树级列表(必须为已组装好的树级结构集合,不能是单纯的List集合)
     * @param predicate 条件
     */
    static <S extends TreeStructure> void filterTreeIncludeChildren(Collection<S> treeCollection, Predicate<S> predicate){
        if(CollectionUtils.isEmpty(treeCollection)){
            return;
        }
        treeCollection.removeIf(r -> {
            if(predicate.test(r)) return false;
            Collection<S> children = r.getChildren();
            filterTreeIncludeChildren(children, predicate);
            if(CollectionUtils.isEmpty(children)) return true;
            return false;
        });
    }


    /**
     * 树转为list,树里面有多少数据就转多少数据
     *
     * @param tree
     * @param <T>
     * @return
     */
    static <T extends TreeStructure> List<T> treeTransList(List<T> tree) {
        List<T> result = new ArrayList<>();
        Stack<T> executeCurStack = new Stack<>();
        for (T item : tree) {
            result.add(item);
            if (Objects.isNull(item.getChildren()) || CollectionUtils.isEmpty(item.getChildren())) continue;
            item.getChildren().forEach(child -> executeCurStack.push((T) child));
            item.setChildren(null);
            while (!executeCurStack.isEmpty()) {
                if (!CollectionUtils.isEmpty(executeCurStack.peek().getChildren())) {
                    Collection children = executeCurStack.peek().getChildren();
                    executeCurStack.peek().setChildren(null);
                    children.forEach(child -> executeCurStack.push((T) child));
                    continue;
                }
                result.add(executeCurStack.pop());
            }
        }
        return result;
    }

    /**
     *  筛选保留符合条件的树级列表:
     *  <h3>保留符合条件的元素,以及其直接父元素</h3>
     *
     * @param treeCollection 树级列表(必须为已组装好的树级结构集合,不能是单纯的List集合)
     * @param predicate 条件
     */
    static <S extends TreeStructure> void filterTree(Collection<S> treeCollection, Predicate<S> predicate){
        if(CollectionUtils.isEmpty(treeCollection)) return;
        treeCollection.removeIf(r -> {
            Collection<S> children = r.getChildren();
            filterTree(children, predicate);
            if(!CollectionUtils.isEmpty(children)) return false;
            return !predicate.test(r);
        });
    }

    class SortedLinkedList<T extends TreeStructure> extends LinkedList<T> {
        @Override
        public boolean add(T t) {
            if(size() == 0){
                add(0, t);
                return true;
            } else {
                T value = t;
                int x;
                for(x = size(); x > 0; x--){
                    if (value.compareTo(get(x - 1)) > 0){
                        break;
                    }
                }
                add(x, value);
                return true;
            }
        }
    }
}```

## 实体

```java
@Data
public class TreeViewModel implements Serializable, TreeStructure<Long, TreeViewModel> {

    /**
     * id
     */
    private Long id;

    /**
     * 上级id
     */
    private Long parentId;

    /**
     * 名称
     */
    private String name;

    /**
     * 简称
     */
    private String shortName;

    /**
     * 子集资源
     */
    private Collection<TreeViewModel> children;

    /**
     * 显示排序
     */
    private Integer sortIndex;
}

调用方式

  List<TreeViewModel> treeViewModelList = TreeStructure.buildTreeList(viewModelList, findViewTreeModel.getId());

展示效果图类似于这种

在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值