针对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;
}

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