树结构
/**
* 设备树
* @param imsEmBasicinfoDssbList
* @return
*/
public static List<Menu> getree(List<ImsEmBasicinfoDssb> imsEmBasicinfoDssbList){
List<Menu> menus = new ArrayList<>();
imsEmBasicinfoDssbList.parallelStream().forEach(imsEmBasicinfoDssb -> {
if (!StringUtils.isEmpty(imsEmBasicinfoDssb.getNAME()) && !StringUtils.isEmpty(imsEmBasicinfoDssb.getLEVELCODE())){
Menu menu = new Menu();
try {
BeanUtils.copyProperties(menu,imsEmBasicinfoDssb);
} catch (Exception e) {
e.printStackTrace();
}
menus.addAll((Collection<? extends Menu>) menu);
}
});
//根据规律找到树的第0层(当层次码的长度为12时就是树的第0层)
List<Menu> menuList = menus.parallelStream().filter(menu -> menu.getLEVELCODE().length()==12)
.map(menu -> {
menu.setChildren(getChildrens(menu,menus));
return menu;
})
.collect(Collectors.toList());
return menuList;
}
/**
* 设备树
* @param menu
* @param all
* @return
*/
public static List<Menu> getChildrens(Menu menu,List<Menu> all){
List<Menu> menuList = all.parallelStream()
.filter(menu1 -> { //根据规律找到数据子节点(树的每个下级节点的层次码都会包含上级节点的层次码并且下级节点的层次码的长度都会加上3位)
return menu1.getLEVELCODE().contains(menu.getLEVELCODE())
&& menu1.getLEVELCODE().length() == (menu.getLEVELCODE().length() +3);
})
.map(menu1 -> {//使用递归查找下级节点
menu1.setChildren(getChildrens(menu1,all));
return menu1;
})
.collect(Collectors.toList());
return menuList;
}
package com.ims.common.utils;
import java.util.List;
public class Menu {
private Integer ID;
private String NAME;
//层次码
private String LEVELCODE;
//设备树子节点
private List<Menu> children;
@Override
public String toString() {
return "Menu{" +
"ID=" + ID +
", NAME='" + NAME + '\'' +
", LEVELCODE='" + LEVELCODE + '\'' +
", children=" + children +
'}';
}
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME = NAME;
}
public String getLEVELCODE() {
return LEVELCODE;
}
public void setLEVELCODE(String LEVELCODE) {
this.LEVELCODE = LEVELCODE;
}
public List<Menu> getChildren() {
return children;
}
public void setChildren(List<Menu> children) {
this.children = children;
}
}