记一下自己在展示树状结构时候的几个写法,一个是确定有几个层级的,用于只有两三个层级的树状结构,写法简单一点。还有就是不确定有几个层级,也可能1个,也可能4个或者更多。
先说一下确定有几个层级的写法
这是需要用的树状结构实体类
//父级菜单id
private Long id;
//父级菜单名称
private String label;
//子菜单信息
private List children;
public TreeSelect() {
}
public TreeSelect(XXX xxx) {
this.id = xxx.getId();
this.label = xxx.gexxname();
this.professorName = xxx.getxxxame();
this.children = xxx.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());
}
明确几个层级的写法(这里是只有两级),做了两个foreach
//入参的list是查询出来的父级菜单的信息 public ListtreeSelectList(List indexInfoList) { List treeSelectList = new ArrayList<>(); indexInfoList.stream().forEach(e -> { TreeSelect treeSelect = new TreeSelect(); //设置大类信息 if (e.getIndexPid() == 0) { treeSelect.setId(e.getId()); treeSelect.setLabel(e.getIndexPname()); List secondTree = new ArrayList<>(); //根据id查询小类信息 QueryWrapper queryWrapper = new QueryWrapper () .eq("id", e.getId()); List indexInfos = indexInfoMapper.selectList(queryWrapper); //设置小类信息 indexInfos.stream().forEach(indexInfo -> { TreeSelect secondTreeSelect = new TreeSelect(); secondTreeSelect.setId(indexInfo.getId()); secondTreeSelect.setLabel(indexInfo.getIndexPname()); secondTree.add(secondTreeSelect); }); //添加集合 treeSelect.setChildren(secondTree); treeSelectList.add(treeSelect); } }); return treeSelectList; }
下面是不确定几个层级,递归写法
方法类:
public List treeSelectList(List indexInfoList) {
List trees = buildIndexTree(indexInfoList);
return trees.stream().map(TreeSelect::new).collect(Collectors.toList());
}
public List buildIndexTree(List indexInfoList) {
List returnList = new ArrayList();
List indexList = new ArrayList();
//一级菜单设置信息
for (IndexInfo indexInfo : indexInfoList) {
indexList.add(indexInfo.getId());
}
for (Iterator iterator = indexInfoList.iterator(); iterator.hasNext(); ) {
IndexInfo indexInfo =iterator.next();
// 如果是顶级节点, 遍历该父节点的所有子节点
if (!indexList.contains(indexInfo.getIndexPid())) {
recursionFn(indexInfoList, indexInfo);
returnList.add(indexInfo);
}
}
if (returnList.isEmpty()) {
returnList = indexInfoList;
}
return returnList;
}
private void recursionFn(List list, IndexInfo t) {
// 得到子节点列表
List childList = getChildList(list, t);
t.setChildren(childList);
for (IndexInfo tChild : childList) {
if (hasChild(list, tChild)) {
recursionFn(list, tChild);
}
}
}
private List getChildList(List list, IndexInfo t) {
List tlist = new ArrayList();
Iterator it = list.iterator();
while (it.hasNext()) {
IndexInfo n = it.next();
if (StringUtils.isNotNull(n.getIndexPid()) && n.getIndexPid().longValue() == t.getId().longValue()) {
tlist.add(n);
}
}
return tlist;
}
private boolean hasChild(List list, IndexInfo t) {
return getChildList(list, t).size() > 0 ? true : false;
}
附上结果:
"msg": "操作成功",
"code": 200,
"data": [
{
"id": 1,
"label": "指标名称1"
"children": [
{
"id": 4,
"label": "指标名称1-1"
"children": [
{
"id": 10,
"label": "指标名称1-1-1"
},
{
"id": 11,
"label": "指标名称1-1-2"
}
]
},
{
"id": 5,
"label": "指标名称1-2"
}
]
}
]
}



