当前位置:编程学习 > JAVA >>

Java树形数据(或者说级联)分类

- 这几天做东西时遇到一个树形数据(或者说级联,不会形容了,就这么叫吧)分类的问题,开始有点纠结,后想到了一种方法实现,先分享出来,高手勿喷。

正文开始
现有三个类:分别是Chapter.java Section.java KnowledgePoint.java
Chapter.java
private Set sections = new HashSet(0);
public Set getSections() {
        return this.sections;
    }

public void setSections(Set sections) {
        this.sections = sections;
    }
Section.java
private Chapter chapter;
private Set knowledgePoints = new HashSet(0);
public Chapter getChapter() {
        return this.chapter;
    }

public void setChapter(Chapter chapter) {
        this.chapter = chapter;
    }
public Set getKnowledgePoints() {
        return this.knowledgePoints;
    }

public void setKnowledgePoints(Set knowledgePoints) {
        this.knowledgePoints = knowledgePoints;
    }

KnowledgePoint.java
private Section section;
public Section getSection() {
        return this.section;
    }

public void setSection(Section section) {
        this.section = section;
    }

可以看出 章节 有多个小节,小节有多个知识点。当取得知识点后怎么根据不同的章节和小节分类呢?

List<KnowledgePoint> kps = this.allService.getKnowledgePointService()
                .findPoints(kpIds);//取得所选择的知识点
            /** *//********** 根据小节分类知识点 **********/            Map<Integer, Section> map = new HashMap<Integer, Section>();
        for (int i = 0; i < kps.size(); i++) {
            Section section = kps.get(i).getSection();
            Integer key = section.getId();
            if (!map.containsKey(key)) {
                section.getKnowledgePoints().clear();
                map.put(key, section);
            }
            map.get(key).getKnowledgePoints().add(kps.get(i));
        }
        /** *//********** 根据章节分类小节 **********/
            Map<Integer, Chapter> cpMap = new HashMap<Integer, Chapter>();
        Iterator<Section> it = map.values().iterator();
        while (it.hasNext()) {
            Section section = it.next();
            Chapter chapter = section.getChapter();
            Integer key = chapter.getId();
            if (!cpMap.containsKey(key)) {
                chapter.getSections().clear();
                cpMap.put(key, chapter);
            }
            cpMap.get(key).getSections().add(section);
        }

 

 

作者 阿飞

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,