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);
}
正文開始
現有三個類:分別是Chapter.java Section.java KnowledgePoint.java
Chapter.java








Section.java

















KnowledgePoint.java









可以看出 章節 有多個小節,小節有多個知識點。當取得知識點后怎么根據不同的章節和小節分類呢?

























posted on 2012-05-29 21:41 feezh 閱讀(2594) 評論(1) 編輯 收藏 所屬分類: Java相關