New feature of Java 8 - Traversal tree structure using Stream stream recursion
/** * Menu * * @author lcry * @date 2020/06/01 20:36 */ @Data @Builder public class Menu { /** * id */ public Integer id; /** *Name */ public String name; /** *Parent ID, root node is 0 */ public Integer parentId; /** *Child node information */ 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(){ //Simulate the query from the database List<Menu> menus = Arrays.asList( New Menu (1, "root node", 0), New Menu (2, "sub node 1", 1), New Menu (3, "sub node 1.1", 2), New Menu (4, "child node 1.2", 2), New Menu (5, "root node 1.3", 2), New Menu (6, "root node 2", 1), New Menu (7, "root node 2.1", 6), New Menu (8, "root node 2.2", 6), New Menu (9, "root node 2.2.1", 7), New Menu (10, "root node 2.2.2", 7), New Menu (11, "root node 3", 1), New Menu (12, "root node 3.1", 11) ); //Get Parent Node 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 ("------ Convert to json output results ------"); System.out.println(JSON.toJSON(collect)); } /** *Recursive Query Child Node *@ param root root node *@ param all All nodes *@ return Root node information */ 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; }