@Data
@AllArgsConstructor
public class TreeDto {
private String id;
private String name;
private String pid;
private String isParent;
private List<TreeDto> childTreeDto;
}
public class TreeToolUtils {
private List<TreeDto> rootList; //根节点对象存放到这里
private List<TreeDto> bodyList; //其他节点存放到这里,可以包含根节点
public TreeToolUtils(List<TreeDto> rootList, List<TreeDto> bodyList) {
this.rootList = rootList;
this.bodyList = bodyList;
}
public List<TreeDto> getTree(){ //调用的方法入口
if(bodyList != null && !bodyList.isEmpty()){
//声明一个map,用来过滤已操作过的数据
Map<String,String> map = Maps.newHashMapWithExpectedSize(bodyList.size());
rootList.forEach(beanTree -> getChild(beanTree,map));
return rootList;
}
return null;
}
public void getChild(TreeDto treeDto,Map<String,String> map){
List<TreeDto> childList = Lists.newArrayList();
bodyList.stream()
.filter(c -> !map.containsKey(c.getId()))
.filter(c ->c.getPid().equals(treeDto.getId()))
.forEach(c ->{
map.put(c.getId(),c.getPid());
getChild(c,map);
childList.add(c);
});
treeDto.setChildTreeDto(childList);
}
}
TreeDto treeDto = new TreeDto("1", "总店", "null", "true",null);
TreeDto treeDto1 = new TreeDto("2", "市分店", "1", "true",null);
TreeDto treeDto2 = new TreeDto("3", "县分店", "2", "true",null);
TreeDto treeDto3 = new TreeDto("710", "店长", "3", "true",null);
TreeDto treeDto4= new TreeDto("713", "财务部", "3", "true",null);
TreeDto treeDto5 = new TreeDto("20032", "后勤部", "3", "true",null);
TreeDto treeDto6 = new TreeDto("1909", "小王", "710", "false",null);
TreeDto treeDto7= new TreeDto("1974", "小张", "713", "false",null);
TreeDto treeDto8 = new TreeDto("388187", "佳佳", "20032", "false",null);
TreeDto treeDto9 = new TreeDto("1949", "阿达", "20032", "false",null);
ArrayList<TreeDto> rootList = new ArrayList<>();//根节点
ArrayList<TreeDto> bodyList = new ArrayList<>();//子节点
rootList.add(treeDto);
bodyList.add(treeDto1);
bodyList.add(treeDto2);
bodyList.add(treeDto3);
bodyList.add(treeDto4);
bodyList.add(treeDto5);
bodyList.add(treeDto6);
bodyList.add(treeDto7);
bodyList.add(treeDto8);
bodyList.add(treeDto9);
TreeToolUtils utils = new TreeToolUtils(rootList,bodyList);
List<TreeDto> result = utils.getTree();
String jsonString = JSONObject.toJSONString(result.get(0));
System.out.println(jsonString);
}