为了易读没有用Steam流( ̄▽ ̄")
绝对不是因为我不太会用

        //亲友大佬写的流方法,但是好像过滤不掉空节点?可以留做参考( ̄▽ ̄")
        List<Integer> list1 = {5, 22};
        knowTree.stream().map(tscKnowLedge ->tscKnowLedge.getChildren().removeAll(
                tscKnowLedge.getChildren().stream().filter(tscKnowLedge1 ->
                        (!(list1.contains(tscKnowLedge1.getId()))&&tscKnowLedge1.getChildren().size()==0)).collect(Collectors.toList()))).collect(Collectors.toList());

数据库格式
数据库是这样的,有树结构列(其实直接存成数组不也挺好( ̄▽ ̄"))和父节点id列~
entity我就不放了,就是数据库这种外加一个
@TableField(exist = false)
private List<TscChapter> children;
树形结构都这么存

前端树结构用的Vue的element-ui的Tree 树形控件

效果图:

过滤前:
过滤前
过滤后:
过滤后

不要问我为啥最后要显示个树形的结构而不用(xx/xx/xx),问就是产品的要求

// Controller 里边的部分
// Service按照树结构查出树
List<TscChapter> chapterTree = tscChapterService.queryChapterTree(0);
//假设要查的节点的id
int[] a = {5, 22};
// 建个set存储需要查询节点的id及其父节点的id并去重
Set<String> ids = new HashSet<>();
for (int i = 0; i < a.length; i++) {
 TscChapter tscChapter = tscChapterService.getOneTscChapter(a[i]);
    if (!ObjectUtils.isEmpty(tscChapter)) {
 List<String> strings = Arrays.asList(tscChapter.getStructure().split("-"));
        ids.addAll(strings);
    }
}
// 调用方法过滤
treeFilter(chapterTree, ids);
//自己写的过滤方法
public List<TscChapter> treeFilter(List<TscChapter> list, Set<String> set) {
 TscChapter tscChapter;
    Iterator<TscChapter> iterator = list.iterator();
    while (iterator.hasNext()) {
        tscChapter = iterator.next();
        String s = tscChapter.getId().toString();
        if (!set.contains(s)) {
            iterator.remove();
            continue;
        }
        if (tscChapter.getChildren().size() != 0) {
            Iterator<TscChapter> iterator1 = tscChapter.getChildren().iterator();
            while (iterator1.hasNext()) {
                TscChapter next = iterator1.next();
                if (!set.contains(next.getId().toString())) {
                    iterator1.remove();
                    continue;
                }
                if (next.getChildren().size() != 0) {
                    treeFilter(next.getChildren(), set);
                }
            } 
        } 
    } 
    return list;
}

dpd384
1 声望0 粉丝

引用和评论

0 条评论