java 根据 根节点及所有子成员 构造树tree
实体类entity
package com.ompa.biz.entity; import java.util.ArrayList; import java.util.List; public class TreeEntity { private String id; private String name; private String fatherId; private int level; private boolean isleaf; private List<TreeEntity> childList = new ArrayList<TreeEntity>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFatherId() { return fatherId; } public void setFatherId(String fatherId) { this.fatherId = fatherId; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public boolean isIsleaf() { return isleaf; } public void setIsleaf(boolean isleaf) { this.isleaf = isleaf; } public List<TreeEntity> getChildList() { return childList; } public void setChildList(List<TreeEntity> childList) { this.childList = childList; } }
构造树util,调用时直接调用getTreeList(父节点,父节点下所有的子成员)
package com.ompa.utils; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.CollectionUtils; import com.ompa.biz.entity.TreeEntity; /** * 树结构工具类 * <p>Title:TreeUtil </p> * @author zhangcd * @date 2016年11月10日 */ public class TreeUtil { /** * 根据父节点,将子节点一次累计起来 * @author zhangcd * @date 2016年11月10日上午9:40:33 * @param root * @param childList * @return */ public TreeEntity getTreeList(TreeEntity root,List<TreeEntity> childList){ root.setLevel(1); findChildren(root,childList); return root; } private List<TreeEntity> findChildren(TreeEntity root, List<TreeEntity> allNodes) { List<TreeEntity> children = new ArrayList<TreeEntity>(); for (TreeEntity comparedOne : allNodes) { if (comparedOne.getFatherId().equals(root.getId())) { root.getChildList().add(comparedOne); comparedOne.setLevel(root.getLevel() + 1); children.add(comparedOne); } } List<TreeEntity> notChildren = (List<TreeEntity>) CollectionUtils.subtract(allNodes, children); for (TreeEntity child : children) { List<TreeEntity> tmpChildren = findChildren(child, notChildren); if (tmpChildren == null || tmpChildren.size() < 1) { child.setIsleaf(true); } else { child.setIsleaf(false); } // child.setChildren(tmpChildren); } return children; } /** * 得到深度 * * @author zhangcd * @date 2016-6-13 * @param rowspan * @param step * @return */ private int getrowspan(int rowspan,TreeEntity step){ if(step.getChildList() != null && step.getChildList().size()>0){ for(TreeEntity steps:step.getChildList()){ if(rowspan < steps.getLevel()){ rowspan = steps.getLevel(); } rowspan = getrowspan(rowspan,steps); } } return rowspan; } /** * 合并列数 * * @author zhangcd * @date 2016-6-12 * @param colspan * @param step * @return */ private int getcolspan(int colspan,TreeEntity step){ if(step.getChildList() != null && step.getChildList().size()>0){ for(TreeEntity steps:step.getChildList()){ colspan = getcolspan(colspan,steps); } }else{ colspan ++; } return colspan; } }