Java递归实现多级菜单
实体类
public class LabelManage {
@TableId("ID")
private String id;
@TableField("LABEL_NAME")
private String labelName;
@TableField("PARENT_ID")
private String parentId;
@TableField("PARENT_NAME")
private String parentName;
@TableField("LABEL_STATUS")
private Integer labelStatus;
@TableField("IS_PUBLIC")
private Integer isPublic;
@TableField("IS_MUTUALLY_EXCLUSIVE")
private Integer isMutuallyExclusive;
@TableField("SORT_NUM")
private Integer sortNum;
@TableField("DESCRIPTION")
private String description;
@TableField("DELETED_ID")
private String deletedId;
@TableField("DELETED_TIME")
private Date deletedTime;
@TableField(exist = false)
private List<LabelManage> children;
}
生成树菜单
@Override
public List<LabelManage> treeList(Map<String, String> params) {
List<LabelManage> list = mapper.getTreeList(params);
List<LabelManage> rootMenu = new ArrayList<>();
for (LabelManage entity : list) {
if (entity.getParentId().equals("-1")) {
rootMenu.add(entity);
}
}
rootMenu.sort(Comparator.comparing(LabelManage::getCreateTime).reversed());
for (LabelManage entity : rootMenu) {
List<LabelManage> childList = buildTree(entity.getId(), list);
entity.setChildren(childList);
}
return rootMenu;
}
public List<LabelManage> buildTree(String id, List<LabelManage> allMenu) {
List<LabelManage> childList = new ArrayList<>();
for (LabelManage entity : allMenu) {
if (entity.getParentId().equals(id)) {
childList.add(entity);
}
}
for (LabelManage entity : childList) {
entity.setChildren(buildTree(entity.getId(), allMenu));
}
childList.sort(Comparator.comparing(LabelManage::getCreateTime).reversed());
if (childList.size() == 0) {
return new ArrayList<>();
}
return childList;
}
效果展示