將一個list轉化成一顆樹的輸出方法

1.新建一個TreeUtil的類java

package com.zdnst.common.infra.utils;

import java.util.*;

/**
 * 把一個list集合,裏面的bean含有 parentId 轉爲樹形式
 *
 */
public class TreeUtil {

   /**
    * 判斷兩個父ID是否相同
    * @param p1
    * @param p2
    * @return
    */
   private boolean isEqualsParentId(Object p1,Object p2){
      if(p1!=null && p1!=null){
         return p1.equals(p2);
      }else if(p1==null && p2 == null) {
         return true;
      }else if(p1==null && p2 != null) {
         if("".equals(p2.toString())){
            return true;
         }else{
            return false;
         }
      }else if(p1!=null && p2 == null) {
         if("".equals(p1.toString())){
            return true;
         }else{
            return false;
         }
      }else{
         return false;
      }
   }
   
   /**
    * 根據父節點的ID獲取全部子節點,該方法頂級節點必須爲空
    * @param list 分類表
    * @param parentId 傳入的父節點ID
    * @return String
    */
   public List<TreeObject> getChildTreeObjects(List<TreeObject> list,Object parentId) {
      List<TreeObject> returnList = new ArrayList<TreeObject>();
      if(list!=null&&list.size()>0) {

         for (Iterator<TreeObject> iterator = list.iterator(); iterator.hasNext(); ) {
            TreeObject t = (TreeObject) iterator.next();
            // 1、根據傳入的某個父節點ID,遍歷該父節點的全部子節點
            if (isEqualsParentId(t.getParentId(), parentId)) {
               recursionFn(list, t);
               returnList.add(t);
            }
         }
         if(returnList==null||returnList.size()==0){//若是返回出空結果,則說明非樹,直接返回原來結果
            for (Iterator<TreeObject> iterator = list.iterator(); iterator.hasNext(); ) {
               TreeObject t = (TreeObject) iterator.next();
               returnList.add(t);
            }
         }

      }
      return returnList;
   }

   /**
    * 根據父節點的ID獲取全部子節點,該方法頂級節點能夠不爲空,非樹直接返回
    * @param list 分類表
    * @return String
    */
   public List<TreeObject> getChildTreeObjects(List<TreeObject> list) {
      if(list!=null&&list.size()>0) {
         List<TreeObject> topList=new ArrayList<>();
         List<TreeObject> subList=new ArrayList<>();

         Map<String,String> idMap=new HashMap<>();

         for (Iterator<TreeObject> iterator = list.iterator(); iterator.hasNext(); ) {
            //歸併全部list的id集合
            TreeObject t = (TreeObject) iterator.next();
            if(t.getId()!=null){
               idMap.put(t.getId().toString(), t.getId().toString());
            }
         }

         for (Iterator<TreeObject> iterator = list.iterator(); iterator.hasNext(); ) {
            //獲取最頂級的list
            TreeObject t = (TreeObject) iterator.next();
            if(t.getParentId()==null||StringUtils.isEmpty(t.getParentId().toString())){
               topList.add(t);
            }else{
               String id=idMap.get(t.getParentId().toString());
               if(StringUtils.isEmpty(id)){
                  topList.add(t);
               }else{
                  subList.add(t);
               }
            }
         }
         if(topList!=null&&topList.size()>0&&subList!=null&&subList.size()>0){
            List<TreeObject> resultList=new ArrayList<>();
            for (TreeObject t:topList) {
               //將兒子級別的list歸併到頂級中
               List<TreeObject> subOneList=new ArrayList<>();

               for (TreeObject sub:subList) {
                  // 1、根據傳入的某個父節點ID,遍歷該父節點的全部子節點
                  if (isEqualsParentId(sub.getParentId(), t.getId())) {
                     recursionFn(subList, sub);
                     subOneList.add(sub);
                  }
               }
               if(subOneList!=null&&subOneList.size()>0) {
                  t.setChildren(subOneList);
               }

               resultList.add(t);
            }
            return resultList;
         }else{
            return list;
         }
      }
      return list;
   }

   
   /**
    * 遞歸列表
    * @author lanyuan
    * Email: mmm333zzz520@163.com
    * @date 2013-12-4 下午7:27:30
    * @param list
    * @param t
    */
   private void  recursionFn(List<TreeObject> list, TreeObject t) {
      List<TreeObject> childList = getChildList(list, t);// 獲得子節點列表
      t.setChildren(childList);
      for (TreeObject tChild : childList) {
         if (hasChild(list, tChild)) {// 判斷是否有子節點
            //returnList.add(TreeObject);
            Iterator<TreeObject> it = childList.iterator();
            while (it.hasNext()) {
               TreeObject n = (TreeObject) it.next();
               recursionFn(list, n);
            }
         }
      }
   }
   
   // 獲得子節點列表
   private List<TreeObject> getChildList(List<TreeObject> list, TreeObject t) {
      
      List<TreeObject> tlist = new ArrayList<TreeObject>();
      Iterator<TreeObject> it = list.iterator();
      while (it.hasNext()) {
         TreeObject n = (TreeObject) it.next();
         if (isEqualsParentId(n.getParentId(),t.getId())) {
            tlist.add(n);
         }
      }
      return tlist;
   } 
   List<TreeObject> returnList = new ArrayList<TreeObject>();
   /**
     * 根據父節點的ID獲取全部子節點
     * @param list 分類表
     * @param parentId 傳入的父節點ID
     * @param prefix 子節點前綴
     */
    public List<TreeObject> getChildTreeObjects(List<TreeObject> list, Object parentId,String prefix){
        if(list == null) return null;
        for (Iterator<TreeObject> iterator = list.iterator(); iterator.hasNext();) {
            TreeObject node = (TreeObject) iterator.next();
            // 1、根據傳入的某個父節點ID,遍歷該父節點的全部子節點
            if (isEqualsParentId(node.getParentId(),parentId)) {
                recursionFn(list, node,prefix);
            }
            // 2、遍歷全部的父節點下的全部子節點
            /*if (node.getParentId()==0) {
                recursionFn(list, node);
            }*/
        }
        return returnList;
    }
     
    private void recursionFn(List<TreeObject> list, TreeObject node,String p) {
        List<TreeObject> childList = getChildList(list, node);// 獲得子節點列表
        if (hasChild(list, node)) {// 判斷是否有子節點
            returnList.add(node);
            Iterator<TreeObject> it = childList.iterator();
            while (it.hasNext()) {
                TreeObject n = (TreeObject) it.next();
                n.setName(p+n.getName());
                recursionFn(list, n,p+p);
            }
        } else {
            returnList.add(node);
        }
    }

   // 判斷是否有子節點
   private boolean hasChild(List<TreeObject> list, TreeObject t) {
      return getChildList(list, t).size() > 0 ? true : false;
   }
   
   // 本地模擬數據測試
   public void main(String[] args) {
      /*long start = System.currentTimeMillis();
      List<TreeObject> TreeObjectList = new ArrayList<TreeObject>();
      
      TreeObjectUtil mt = new TreeObjectUtil();
      List<TreeObject> ns=mt.getChildTreeObjects(TreeObjectList,0);
      for (TreeObject m : ns) {
         System.out.println(m.getName());
         System.out.println(m.getChildren());
      }
      long end = System.currentTimeMillis();
      System.out.println("用時:" + (end - start) + "ms");*/
   }
   
}

2.新建類TreeObjectnode

package com.zdnst.common.infra.utils;

import java.util.List;

/**
 * 這個是列表樹形式顯示的接口
 */
public interface TreeObject {

   public Object getId();

   public void setId(Object id);

   public Object getParentId();

   public void setParentId(Object parentId);

   public String getName();

   public void setName(String name);

   public List getChildren();

   public void setChildren(List children);

}

 

3.具體列表實體PubCompTypeDto實現TreeObject :app

package com.zdnst.core.sys.application.dto;

import com.zdnst.common.infra.dto.BaseDto;
import com.zdnst.common.infra.utils.TreeObject;

import java.util.List;

public class PubCompTypeDto extends BaseDto  implements TreeObject {
    private static final long serialVersionUID = 5726287409752473211L;

    private String comTypeItemCode;//公司類型CODE,由類型key+具體code組合

    private String comTypeItemName;//類型項名稱

    private String comTypeItemDesc;//類型項描述

    private String parentCode;//父id

    private Long comTypeItemStatus;//1啓用0停用

    /**
     * 類型KEY:
     * 環節:FN_LEAVE_CODE
     * 物品:FN_GOODS_CODE
     * 場地:FN_FIELD_CODE
     * 車輛:FN_CAR_CODE
     */
    private String comTypeKey;

    private String companyId;//公司id

    private Long seqNo;

    private List children;//構造樹使用

    public String getComTypeItemCode() {
        return comTypeItemCode;
    }

    public void setComTypeItemCode(String comTypeItemCode) {
        this.comTypeItemCode = comTypeItemCode == null ? null : comTypeItemCode.trim();
    }

    public String getComTypeItemName() {
        return comTypeItemName;
    }

    public void setComTypeItemName(String comTypeItemName) {
        this.comTypeItemName = comTypeItemName == null ? null : comTypeItemName.trim();
    }

    public String getComTypeItemDesc() {
        return comTypeItemDesc;
    }

    public void setComTypeItemDesc(String comTypeItemDesc) {
        this.comTypeItemDesc = comTypeItemDesc == null ? null : comTypeItemDesc.trim();
    }

    public String getParentCode() {
        return parentCode;
    }

    public void setParentCode(String parentCode) {
        this.parentCode = parentCode == null ? null : parentCode.trim();
    }

    public Long getComTypeItemStatus() {
        return comTypeItemStatus;
    }

    public void setComTypeItemStatus(Long comTypeItemStatus) {
        this.comTypeItemStatus = comTypeItemStatus;
    }

    public String getComTypeKey() {
        return comTypeKey;
    }

    public void setComTypeKey(String comTypeKey) {
        this.comTypeKey = comTypeKey == null ? null : comTypeKey.trim();
    }

    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId == null ? null : companyId.trim();
    }

    public Long getSeqNo() {
        return seqNo;
    }

    public void setSeqNo(Long seqNo) {
        this.seqNo = seqNo;
    }

    @Override
    public Object getId() {
        return getComTypeItemCode();
    }

    @Override
    public void setId(Object id) {
        setComTypeItemCode((String)id);
    }

    @Override
    public Object getParentId() {
        return getParentCode();
    }

    @Override
    public void setParentId(Object parentId) {
        setParentCode((String)parentId);
    }

    @Override
    public String getName() {
        return getComTypeItemName();
    }

    @Override
    public void setName(String name) {
        setComTypeItemName(name);
    }

    @Override
    public List getChildren() {
        return this.children;
    }

    @Override
    public void setChildren(List children) {
        this.children = children;
    }
}

4.在使用中以下調用:ide

TreeUtil treeUtil = new TreeUtil();
List<TreeObject> treeList = treeUtil.getChildTreeObjects(pubCompTypeDtoList);
return JsonView.dataToJson(treeList, response);
相關文章
相關標籤/搜索