当前位置: 首页 > 后端技术 > Java

java训练Stream遍历树结构案例分享

时间:2023-04-02 10:25:13 Java

平时可能会遇到一些需求,比如建一个菜单,建一个树结构,数据库一般用parentid来表示。为了减少对数据库的查询压力,我们可以使用Java8中的Stream一次性的把数据查出来,然后再通过Stream处理,一起来看看吧。为了实现简单的代码实现,模拟查看数据库中的所有数据,放在List_java训练中。实体类:Menu.java/**Menu*@authorlcry*/@Data@BuilderpublicclassMenu{/**id*/publicIntegerid;/**name*/publicStringname;/**parentid,root节点为0*/publicIntegerparentId;/**子节点信息*/publicList

childList;publicMenu(Integerid,Stringname,IntegerparentId){this.id=id;this.name=name;this.parentId=parentId;}publicMenu(Integerid,Stringname,IntegerparentId,ListchildList){this.id=id;this.name=name;this.parentId=parentId;this.childList=childList;}}递归组装树结构:@Testpublicvoidtesttree(){//模拟从数据库查询Listmenus=Arrays.asList(newMenu(1,"rootnode",0),newMenu(2,"子节点1",1),newMenu(3,"子节点1.1",2),newMenu(4,"子节点1.2",2),newMenu(5,"根节点1.3",2),newMenu(6,"rootnode2",1),newMenu(7,"rootnode2.1",6),newMenu(8,"rootnode2.2",6),newMenu(9,"rootnode2.2.1",7),newMenu(10,"rootnode2.2.2",7),newMenu(11,"rootnode3",1),newMenu(12,"rootnode3.1",11));//获取父节点Listcollect=menus.stream().filter(m->m.getParentId()==0).map((m)->{m.setChildList(getChildrens(m,menus));returnm;}).collect(Collectors.toList());System.out.println("--------转json输出结果------");System.out.println(JSON.toJSON(collect));}/**递归查询子节点@paramroot根节点@paramall所有节点@return根节点信息*/privateListgetChildrens(Menuroot,Listall){Listchildren=all.stream().filter(m->{returnObjects.equals(m.getParentId(),root.getId());}).map((m)->{m.setChildList(getChildrens(m,all));returnm;}).collect(Collectors.toList());returnchildren;}格式化打印结果:文章转载自Java编程