1.首先传统方式是使用递归遍历树型菜单,可以这么理解就是先获取跟节点然后在获取子节点。
编写实体类
@Data
@Builder
public class mout {
private Integer id;
private String name;
private Integer parentId;
private List<mout> childList;
public mout(Integer id,String name,Integer parentId){
this.id=id;
this.name=name;
this.parentId=parentId;
}
public mout(Integer id,String name,Integer parentId,List<mout> childList){
this.id=id;
this.name=name;
this.parentId=parentId;
this.childList=childList;
}
}
@Test
public void tetxt1() {
//模拟数据库查询数据
final List<mout> moutList = Arrays.asList(
new mout(1, "跟节点", 0)
,new mout(2,"更节点子的节点1",1),
new mout(3,"子节点1-1",1),
new mout(4,"子节点1-2",2),
new mout(5,"子节点2",2),
new mout(6,"子节点2-1",3));
//遍历获取跟节点,并且添加子节点
final List<mout> collect = moutList.stream().filter(m -> m.getParentId() == 0).map((m) -> {
m.setChildList(getchildList(m, moutList));
return m;
}).collect(Collectors.toList());
final Object o = JSON.toJSON(collect);
System.out.println(o);
}
//获取子节点
@Test
public List<mout> getchildList(mout mout,List<mout> moutList){
final List<com.baidu.entity.mout> collect = moutList.stream().filter(mout1 -> {
return Objects.equals(mout1.getParentId(), mout.getId());
}).map(mout1 -> {
mout1.setChildList(getchildList(mout1, moutList));
return mout1;
}
).collect(Collectors.toList());
return collect;
}