遞迴遍歷樹狀結構優雅實現
實體:
@Data
@Builder
public class Menu {
private Integer id;
private String name;
private Integer parentId;
private List<Menu> childrenList;
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> childrenList) {
this.id = id;
this.name = name;
this.parentId = parentId;
this.childrenList = childrenList;
}
}
實現:
@SpringBootTest
public class RecursionTest {
@Test
public void recursion() {
List<Menu> menus = Arrays.asList(
new Menu(1, "根節點", 0),
new Menu(2, "子節點1", 1),
new Menu(3, "子節點1.1", 2),
new Menu(4, "子節點1.2", 2),
new Menu(5, "根節點1.3", 2),
new Menu(6, "根節點2", 1),
new Menu(7, "根節點2.1", 6),
new Menu(8, "根節點2.2", 6),
new Menu(9, "根節點2.2.1", 7),
new Menu(10, "根節點2.2.2", 7),
new Menu(11, "根節點3", 1),
new Menu(12, "根節點3.1", 11));
// 獲取父節點
List<Menu> collect = menus.stream()
.filter(m -> m.getParentId() == 0)
.peek((m) -> m.setChildrenList(getChildren(m, menus)))
.collect(Collectors.toList());
System.out.println(JSONUtil.toJsonStr(collect));
}
private List<Menu> getChildren(Menu root, List<Menu> all) {
return all.stream()
.filter(m -> Objects.equals(m.getParentId(), root.getId()))
.peek(m -> m.setChildrenList(getChildren(m, all)))
.collect(Collectors.toList());
}
}