今天看到一個貼子非常好,利用java 8 的stream實現組織樹結構的構建
實體類
/**
* Menu
* @author lcry
*/
@Data
@Builder
public class Menu {
/**
* id
*/
public Integer id;
/**
* 名稱
*/
public String name;
/**
* 父id ,根節點為0
*/
public Integer parentId;
/**
* 子節點信息
*/
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;
}
}
測試類
@Test
public void testtree(){
//模擬從數據庫查詢出來
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).map(
(m) -> {
m.setChildList(getChildrens(m, menus));
return m;
}
).collect(Collectors.toList());
System.out.println("-------轉json輸出結果-------");
System.out.println(JSON.toJSON(collect));
}
/**
* 遞歸查詢子節點
* @param root 根節點
* @param all 所有節點
* @return 根節點信息
*/
private List<Menu> getChildrens(Menu root, List<Menu> all) {
List<Menu> children = all.stream().filter(m -> {
return Objects.equals(m.getParentId(), root.getId());
}).map(
(m) -> {
m.setChildList(getChildrens(m, all));
return m;
}
).collect(Collectors.toList());
return children;
}
