- 基本结构对象
- 树形结构对象
- 构建方法
一般树形结构都包含两个关键字段,parentId,children,我的例子中使用的是parent对象,实际使用自己更改即可。
基本结构对象public class Treebase{ @ApiModelProperty(value = "子集") private List children; @ApiModelProperty(value = "父级id") private T parent; @ApiModelProperty(value = "id") private Long id; }
上面这组对象是树形结构的基本结构,如果使用的父级结构是parentId就把 private T parent;改成pring String parentId;即可,另外,只要继承了该结构的对象,都可以调用下面的方法构建树形结构
树形结构对象public class Permission extends Treebase{ ..... 字段无需理会,实际使用不到 ..... }
这是需要构建树形结构的对象,直接继承即可
构建方法public> List listToTree(List tList) { List firstLabelDto = new ArrayList<>(); Map labelMap = tList.stream().collect(Collectors.toMap(T::getId, v->v,(v1, v2)->v1));//将递归对象转化成map,方便查询 for (T t : tList) { if (t.getParent() == null) { firstLabelDto.add(t); } else { labelMap.get(t.getParent().getId()).getChildren().add(t); } } return firstLabelDto; }
如果使用的是parentId,则在使用parent的位置相应更改即可,使用时直接调用,返回结果就是完整的树形结构



