使用lambda表达式快捷完成Tree结构
# 前言
以前在java中构建菜单、区划等都是使用递归或是数据库。 数据库如pg、mysql等原生不支持tree结构,递归不是很好理解,同时代码太长。所以考虑使用java1.8以后支持的lambda操作一波
PS:数据库我使用了mybatis-plus,所以查数据的写法简化了
# 代码
//查找所有菜单,正序排序
List<MenuEntity> list = this.list(Wrappers.lambdaQuery(MenuEntity.class)
.eq(MenuEntity::getHide, BoolStateEnum.FALSE.getCode())
.orderByAsc(MenuEntity::getSort));
//找寻下级菜单,利用.map来保证引用地址相同
list.stream()
.map(ele -> {
ele.setChildren(this.fromTree(ele, list));
return ele;
})
.collect(Collectors.toList());
//过滤出最上级的菜单
return list.stream()
.filter(ele -> ele.getParentId() == null)
.collect(Collectors.toList());
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 找寻指定菜单的下级菜单
*
* @param menuEntity 当前菜单
* @param list 所有的菜单list
* @return 下级菜单
*/
private List<MenuEntity> fromTree(MenuEntity menuEntity, List<MenuEntity> list) {
return list.stream()
.filter(ele -> menuEntity.getId().equals(ele.getParentId()))
.collect(Collectors.toList());
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
public class MenuEntity {
@ApiModelProperty(value = "ID")
@TableId
private Long id;
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
@ApiModelProperty(value = "创建人ID")
private String createUserId;
@ApiModelProperty(value = "修改时间")
private LocalDateTime updateTime;
@ApiModelProperty(value = "修改人ID")
private String updateUserId;
@ApiModelProperty(value = "节点名")
private String name;
@ApiModelProperty(value = "所有上级节点id列表 为空时表示最顶层")
private Long parentId;
@ApiModelProperty(value = "菜单类型 0=节点 1=菜单 2=按钮")
private int menuType;
@ApiModelProperty(value = "图标")
private String icon;
@ApiModelProperty(value = "url")
private String url;
@ApiModelProperty(value = "hash路由")
private String hash;
@ApiModelProperty(value = "是否隐藏 0=不隐藏 1=隐藏")
private int hide;
@ApiModelProperty(value = "排序,从小到大正向排序")
private int sort;
@ApiModelProperty(value = "下级菜单集合")
@TableField(exist = false)
private List<MenuEntity> children;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
编辑 (opens new window)
上次更新: 2024-11-06, 19:27:10