1、菜单类
@Data
public class Menu {
private Long id;
private String name;
private Long pid;
private List<Menu> children;
public Menu(Long id, String name, Long pid) {
this.id = id;
this.name = name;
this.pid = pid;
}
}
2、父id确定情况下生成新的树
public static void test1(){
List<Menu> menuList=new ArrayList<>();
menuList.add(new Menu(1L,"菜单1",0L));
menuList.add(new Menu(2L,"菜单2",1L));
menuList.add(new Menu(3L,"菜单3",2L));
menuList.add(new Menu(4L,"菜单4",5L));
List<Menu> menus=menuList.stream().filter(m->m.getPid()==0).map(m->{
m.setChildren(getChildrens(m,menuList));
return m;
}).collect(Collectors.toList());
System.out.println(JSONUtil.toJsonPrettyStr(menus));
}
3、递归生成子树?
private static List<Menu> getChildrens(Menu root, List<Menu> all) {
List<Menu> children = all.stream().filter(m -> Objects.equals(m.getPid(), root.getId())).map(
(m) -> {
m.setChildren(getChildrens(m, all));
return m;
}
).collect(Collectors.toList());
return children;
}
4、有查询条件树断裂情况下根据id和pid生成新的树
public static void test2(){
List<Menu> menuList=new ArrayList<>();
menuList.add(new Menu(1L,"菜单1",0L));
menuList.add(new Menu(2L,"菜单2",1L));
menuList.add(new Menu(3L,"菜单3",2L));
menuList.add(new Menu(4L,"菜单4",5L));
List<Long> IdList=menuList.stream().map(s->s.getId()).collect(Collectors.toList());
List<Long> PidList=menuList.stream().map(s->s.getPid()).collect(Collectors.toList());
/**
* 求两者的交集
*/
List<Long> jiaoJiIdList=new ArrayList<>();
for(Long id:IdList){
if(PidList.contains(id)){
jiaoJiIdList.add(id);
}
}
/**
* 过滤时所有pid在交集里面的数据,若pid在交集中则说明该元素有父类
*/
List<Menu> menus=menuList.stream().filter(m->!jiaoJiIdList.contains(m.getPid())).map(m->{
m.setChildren(getChildrens(m,menuList));
return m;
}).collect(Collectors.toList());
System.out.println(JSONUtil.toJsonPrettyStr(menus));
}
|