不用递归的情况下将带父节点的表转换为树状结构


将当前单向节点(Menu1) 转换成 树状结构(Java 中为链表,Menu2)

Name Current Node Parent Node
A 1 0
B 2 0
C 3 1
D 4 3
1
2
3
4
5
6
7
8
9
10
11
12
public class Menu1 {
private Long menuId;
private String name;
private Long parentId;

public Menu1(Long menuId, String name, Long parentId) {
this.menuId = menuId;
this.name = name;
this.parentId = parentId;
}
....
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Menu2 {
private Long menuId;
private String name;
private List<Menu2> children;

public Menu2() {
}

public Menu2(Long menuId, String name, List<Menu2> children) {
this.menuId = menuId;
this.name = name;
this.children = children;
}
....
}

具体代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
static List<Menu2> start(List<Menu1> menu1List) {
//找到Root 节点的所有children
Menu2 menu2Root = new Menu2(0L, "ROOT", null);
List<Menu2> topLevelCollection = menu1List.stream()
.filter(data -> data.getParentId().equals(0L))
.map(data->new Menu2(data.getMenuId(), data.getName(), null))
.collect(Collectors.toList());
//添加到 children 属性中
menu2Root.setChildren(topLevelCollection);
//创建队列,把每个节点添加进去
Queue<Menu2> menu2Queue = new LinkedBlockingQueue<>(topLevelCollection);
while (!menu2Queue.isEmpty()){
Menu2 menu2 = menu2Queue.poll();
List<Menu2> menu2collection = menu1List.stream()
.filter(data -> data.getParentId().equals(menu2.getMenuId()))
.map(data->new Menu2(data.getMenuId(), data.getName(), null))
.collect(Collectors.toList());
menu2.setChildren(menu2collection);
menu2Queue.addAll(menu2collection);
}

return menu2Root.getChildren();
}