需求:解决生成树形结构问题
一开始是遍历sql得到效果图,但是如果数据量较大的话对服务器压力较大,并且耗时长,优化在代码中写出树工具类
- 数据库表结构:
area_id | area_name | farth_id |
---|---|---|
101 | xxx | |
105 | w | 101 |
得到最终效果图:
java代码:
SELECT
area_id id,
area_name title,
fath_id fathId
FROM dim_areas
public class TreeUtil {
public static <T extends BaseTreeGrid> List<T> formatTreeInList(List<T> paramList) {
List<T> resultTree = new ArrayList<>();
List<T> childrenNotes = new ArrayList<>();
for (T t : paramList) {
if (StringUtils.isBlank(t.getFathId())) {
resultTree.add(t);
} else {
childrenNotes.add(t);
}
}
for (T fathNote : resultTree) {
List<T> resultGrid = getTreeChildrens(fathNote.getId(), childrenNotes);
fathNote.setChildrens(resultGrid);
fathNote.setFathId("");
}
return resultTree;
}
public static <T extends BaseTreeGrid> List<T> getTreeChildrens(String id, List<T> baseTreeGrids) {
List<T> resultTreeGrids = new ArrayList<T>();
for (T t:baseTreeGrids) {
if (id.equals(t.getFathId())) {
List<T> children = getTreeChildrens(t.getId(), baseTreeGrids);
t.setChild(children);
resultTreeGrids.add(t);
}
}
return resultTreeGrids;
}
public class BaseTreeGrid implements Serializable {
private String id;
private String title;
private String fathId;
private List<?> childrens;
}