針對java實體類的樹形結構,所寫的遞歸

第一種遇到的樹形結構是類似於01,0101,02,0201這種形式的,不知道當初產品經理爲什麼要這種形式的數據結構
/**
* 獲得頂級父類的方法
* @param temp
* @return
/
private List getPL(List temp) {
List result = new ArrayList<>();
for (int i = 0; i < temp.size(); i++) {
if (temp.get(i).getTypeId().length() == 2) {
result.add(temp.get(i));
temp.remove(i);
i–;
}
}
return result;
}
/
*
* 將子節點添加到父節點下的方法
*
* @param cl
* @param pl
/
private void addChildrenToParent(List cl, List pl) {
List parentList = new ArrayList<>();
List childrenList = new ArrayList<>();
int end = pl.get(0).getTypeId().length();
for (AssetType c : cl) {
if (c.getTypeId().length() == pl.get(0).getTypeId().length() + 2) {
String s1 = c.getTypeId().substring(0, end);
for (AssetType p : pl) {
String s2 = p.getTypeId();
if (s1.equals(s2)) {
p.getChildren().add©;
}
}
parentList.add©;
} else {
childrenList.add©;
}
}
if (childrenList.size() != 0) {
addChildrenToParent(childrenList, parentList);
}
}
執行完下面3行代碼後,我們只需要拿到parentList即可,這個集合裏面的數據就是樹形結構
List lists = assetTypeRepository.findAll();
List parentList = getPL(lists);
addChildrenToParent(lists, parentList);
第二種的遞歸數據類型對應mysql的表中的數據是一條數據的主鍵ID是另外一條數據的parentId
/
*
* 獲取父類結點
*
* @param populations
* @return
/
public List getParentPopu(List populations) {
List trees = new ArrayList<>();
for (PopulationVO population : populations) {
if (0 == (population.getParentId())) {
trees.add(findChildren(population, populations));
}
}
return trees;
}
/
*
* 獲取子類結點
*
* @param treeNode
* @param treeNodes
* @return
*/
public PopulationVO findChildren(PopulationVO treeNode, List treeNodes) {
for (PopulationVO population : treeNodes) {
if (treeNode.getId().equals(population.getParentId())) {
treeNode.getChildren().add(findChildren(population, treeNodes));
}
}
return treeNode;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章