We may encounter some requirements in general, such as building menus, building tree structures, and databases are generally represented by the parent ID. To reduce the query pressure of the database, we can use the Stream stream in Java 8 to find out the data at one time, and then use the stream processing. Let's look at it together. In order to achieve simple code implementation, Simulate to view all data in the database into the List.

Entity class: Menu.java

 /** * 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; } }

Recursive assembly tree structure:

 @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; }

Format print results:
 New feature of Java 8 - Traversal tree structure using Stream stream recursion