树形结构数据后台处理:一次循环生成树

来源:互联网 发布:大数据 行业专家 编辑:程序博客网 时间:2024/05/19 16:21

 //一、优化算法下的树结构遍历
  @SuppressWarnings("unchecked")
 public String gainTreeFolder(){
  //1 设置虚拟根节点
  root = new Folders();
  root.setFolderId(MyConstants.ID);
  root.setFolderName("顶部");
  // 2查询该节点下的树形结构的数据.
  List<Folders> fileList = filesService.queryList("Folders", "queryAll",root);
   Map map=new TreeMap<String,Folders>();
  Folders tempTree;
  //3 将list中元素放入map.其中主键为key.
  Folders subRoot=null;
  for(int i=0;fileList!=null&&i<fileList.size();i++){
   tempTree=fileList.get(i);
   map.put(tempTree.getId(), tempTree);
   if(MyConstants.ID.equals(tempTree.getParentId())){
    subRoot=tempTree;
    root.getChildren().add(subRoot);
   }
  }
  //4 循环。将循环中的节点,添加到上一级节点中。
  for(int i=0;fileList!=null&&i<fileList.size();i++){
   tempTree=fileList.get(i);
   Folders t=(Folders)map.get(tempTree.getParentId());
   if(t!=null){
   t.getChildren().add(tempTree);
    map.put(tempTree.getParentId(), t);
   }
  }

    //5返回root.
  return SUCCESS;
 }

 

二、原有算法

// 加载文件夹结构图
 @SuppressWarnings("unchecked")
 public String loadFoldersMap() {

  logger.info("开始文件夹结构图");
  // 1 设置根节点
  root = new Folders();
  root.setFolderId(MyConstants.ID);
  root.setParentId(MyConstants.PARENTID);
  root.setFolderName("顶部");
  root.setOwnerType((short) 9);
  // 2查询该节点下的树形结构的数据.
  List<Folders> fileList = filesService.queryList("Folders", "queryAll",
    root);
  // 3 循环将下级节点数据添加进来
  ConcurrentLinkedQueue<Folders> newList = new ConcurrentLinkedQueue<Folders>();
  newList.addAll(fileList);
  getList(root, newList);
  return SUCCESS;
 }

 public void getList(Folders files, ConcurrentLinkedQueue<Folders> fileLists) {
  List<Folders> sublist = new ArrayList<Folders>();
  if (!MyUtils.isEmpty(fileLists)) {
   for (Iterator<Folders> iterator = fileLists.iterator(); iterator
     .hasNext();) {
    Folders temp = (Folders) iterator.next();
    if (MyUtils.equals(temp.getParentId(), files.getFolderId())) {
     sublist.add(temp);
     iterator.remove();
     getList(temp, fileLists);
    }
   }
  }
  files.setChildren(sublist);
 }

0 1
原创粉丝点击