菜单功能主要的字段设计。(不包含每个功能所需要的业务字段。)
@Data
@Builder
class Menu {
/**
* id
*/
public Integer id;
/**
* 名称
*/
public String name;
/**
* 父id ,根节点为0
*/
public Integer parentId;
/**
* 需要隐藏的菜单
*/
public Boolean hideInMenu;
/**
* 权重 ,根节点为0
*/
public Integer weight;
/**
* 子节点信息
*/
public List<Menu> childList;
public Menu(Integer id, String name, Integer parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
public Menu(Integer id, String name, Integer parentId, List<Menu> childList) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.childList = childList;
}
}
stream流遍历循环处理菜单结构。
@Test
public void dealMenuTest(){
List<Menu> menuList = new ArrayList<>();
//根据业务隐藏菜单。
menuList.stream().filter(m -> !m.getHideInMenu());
List<Menu> collect = menuList.stream().filter(m -> m.getParentId() == 0).map(
(m) -> {
m.setChildList(getChildrens(m, menuList));
return m;
}
).collect(Collectors.toList());
System.out.println("-------转json输出结果-------");
System.out.println(JSON.toJSON(collect));
}
private List<Menu> getChildrens(Menu root, List<Menu> all) {
List<Menu> children = all.stream().filter(m -> Objects.equals(m.getParentId(), root.getId())).map(
(m) -> {
m.setChildList(getChildrens(m, all));
return m;
}
).collect(Collectors.toList());
// 可以配置权重
children.sort((o1, o2) -> o2.getWeight().compareTo(o1.getWeight()));
return children;
}