树的搜索实现(反向遍历)

List<Map<String,Object>> list = new ArrayList<>();
//树原始数据
//定义辅助列表
List<Map<String, Object>> tempList = new ArrayList<>();
List<Map<String, Object>> parentList = new ArrayList<>();
List<TreeVO> resultList = new ArrayList<>();
//转换成map提高查询速度
Map<Object, Map<String, Object>> orgMap = list.parallelStream()
.collect(Collectors.toMap(v -> v.get(id), v -> {
//初始化查询结果
String o = (String) v.getOrDefault(name, "");
if(((String)o).contains(searchStr)){
tempList.add(v);
}
return v;
}));
//遍历获取上级
while(!tempList.isEmpty()){
tempList.forEach(v->{
if(v != null){
Object o = v.get(pid);
if(o == null){
o = "";
}
String vPid = (String)o;
if(!vPid.isEmpty()){
Map<String, Object> parent = orgMap.get(vPid);
if(parent != null){
parentList.add(parent);
}
}
       //定义的树结构
TreeVO vo = new TreeVO();
vo.setId((String) v.get(id));
vo.setName((String) v.get(name));
vo.setType((String) v.get(type));
vo.setCode((String) v.get(code));
vo.setParentId((String) v.get(pid));
if(!resultList.contains(vo)){
resultList.add(vo);
}
}
});
tempList.clear();
tempList.addAll(parentList);
parentList.clear();
}
原文地址:https://www.cnblogs.com/hjm0928/p/11830613.html