JAVA 构造树形菜单
数据如图 P_ORG_NO 是父级节点编号 将此构造成一颗菜单树
public List<OrgVO> buildOrgTree(){
List<OrgVO> orgs = orgMapper.selectAll(dataSourceName);
List<OrgVO> returnList = new ArrayList<>();
List<String> tempList = orgs.stream().map(OrgVO::getOrgNo).collect(Collectors.toList());
for (OrgVO org : orgs) {
// 如果是顶级节点, 遍历该父节点的所有子节点
if (!tempList.contains(org.getPOrgNo())) {
recursionFn(orgs, org);
returnList.add(org);
}
}
if (returnList.isEmpty()) {
returnList = orgs;
}
return returnList;
}
private void recursionFn(List<OrgVO> list, OrgVO t) {
//得到子节点列表
List<OrgVO> childList = getChildList(list, t);
t.setChildrenList(childList);
for (OrgVO tChild : childList) {
if (hasChild(list, tChild)) {
recursionFn(list, tChild);
}
}
}
/**
* 获取子节点
* @param list list
* @param t t
* @return 子节点列表
*/
private List<OrgVO> getChildList(List<OrgVO> list, OrgVO t) {
List<OrgVO> tlist = new ArrayList<>();
for (OrgVO n : list) {
if (n.getPOrgNo().equals(t.getOrgNo())) {
tlist.add(n);
}
}
return tlist;
}
/**
* 判断是否有子节点
*
* @param list list
* @param t t
* @return 判断是否有子节点
*/
private boolean hasChild(List<OrgVO> list, OrgVO t) {
return getChildList(list, t).size() > 0;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class OrgVO {
/**
* 本实体记录的唯一标识
*/
private String orgNo;
/**
* 详细的名称。
*/
private String orgName;
/**
* 直接上级编号。
*/
private String pOrgNo;
/**
* 在同级中的排列顺序的序号,用自然数标识,如,1、2、3
*/
private Integer sortNo;
private String orgShorthand;
/**
* 子级元素
*/
private List<OrgVO> childrenList = new ArrayList<>();
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TreeSelect implements Serializable {
private static final long serialVersionUID = 1567893487236L;
/**
* 本实体记录的唯一标识
*/
private String orgNo;
/**
* 详细的名称。
*/
private String orgName;
/**
* 子节点
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<TreeSelect> childrenList;
public TreeSelect(OrgVO org) {
this.orgNo = org.getOrgNo();
this.orgName = org.getOrgName();
this.childrenList = org.getChildrenList().stream().map(TreeSelect::new).collect(Collectors.toList());
}
}
@GetMapping("/tree")
public CommonResult<OrgVO> orgTree() {
List<OrgVO> orgTree = orgService.buildOrgTree();
return CommonResult.ok("成功", orgTree.get(0));
}
@GetMapping("/nameTree")
public CommonResult<TreeSelect> orgNameTree() {
List<OrgVO> orgTree = orgService.buildOrgTree();
List<TreeSelect> treeSelectList = orgTree.stream()
.map(TreeSelect::new).collect(Collectors.toList());
return CommonResult.ok("成功", treeSelectList.get(0));
}