一个处理树的工具类

闲着没事,写一个处理树的工具类。有需要的可以引用,大神有意见,多多评论。 微笑

里面的Resource对象就是树节点的对象,需要的更换成自己的节点对象。


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.duomei.entity.cmp.Resource;

/**   
 * 类名称:Tree  
 * 类描述:  生成工具类
 * @author 作者:slh
 * @version 1.0.0 
 * 创建时间:2016年12月1日 下午3:37:10  
 * 修改人:  
 * 修改时间:2016年12月1日 下午3:37:10  
 * 修改备注:      
 */
public class Tree {
	
	private List
   
   
    
     nodes;
	
	  
	/**   
	 * 创建一个新的实例 Tree.   
	 *   
	 * @param nodes   将树的所有节点都初始化进来。
	 */
	public Tree(List
    
    
     
      nodes){  
		this.nodes = nodes;
    }
	
	
	/**   
	 * buildTree
	 * 描述:  创建树
	 * @return List
     
     
      
      
       
       >    
	 * @exception    
	 * @since  1.0.0   
	*/
	public List
       
        
        
          > buildTree(){ List 
          
          
            > list = new ArrayList 
            
            
              >(); for(Resource node : nodes) { //这里判断父节点,需要自己更改判断 if (StringUtils.equals(node.getParentid(), "00000")) { Map 
             
               map = new HashMap 
              
                (); map.put("id", node.getId()); map.put("text", node.getResourcename()); List 
                > childs = buildChilds(node); map.put("children", childs); list.add(map); } } return list; } /** * buildChilds * 描述: 创建树下的节点。 * @param node * @return List  > * @exception * @since 1.0.0 */ private List  > buildChilds(Resource node){ List  > list = new ArrayList  >(); List childNodes = getChilds(node); for(Resource childNode : childNodes){ Map map = new HashMap (); map.put("id", childNode.getId()); map.put("text", childNode.getResourcename()); map.put("url", childNode.getResourceurl()); map.put("target", "main"); buildChilds(childNode); list.add(map); } return list; } /** * getChilds * 描述: 获取子节点 * @param parentNode * @return List * @exception * @since 1.0.0 */ public List getChilds(Resource parentNode) { List childNodes = new ArrayList (); String parentId = parentNode.getId(); for(Resource node : nodes){ if (StringUtils.equals(node.getParentid(), parentId)) { childNodes.add(node); } } return childNodes; } public static void main(String[] args) { List list = new ArrayList (); Resource resource1 = new Resource(); resource1.setId("1"); resource1.setParentid("00000"); resource1.setResourcename("node1"); Resource resource2 = new Resource(); resource2.setId("2"); resource2.setParentid("1"); resource2.setResourcename("node2"); list.add(resource1); list.add(resource2); Tree tree = new Tree(list); List  > mapList = tree.buildTree(); System.err.println(mapList); } }       
               
              
             
           
        
      
      
    
    
   
   

猜你喜欢

转载自blog.csdn.net/just3019/article/details/53422588
今日推荐