将数据库树形记录转为java 树形数据结构

    /**
	 * 转换为Tree结构
	 * @param treedata
	 * @return
	 */
	public static Tree toTreeList(List<Tree> treedata){
		Tree root = null;
		for(Tree node:treedata){
			String parentid = node.getParentid();
			if(parentid.equals("0"))
				root = node;
		    Tree parent = getTarget(treedata,parentid); 
		    if(parent != null){
		    	List<Tree> children = parent.getChildren();
		    	if(children == null){
		    		children = new ArrayList<Tree>();
		    		parent.setChildren(children);
		    	}
		        children.add(node);
		    }
		}
		return root;
	}
	/**
	 * 获得指定节点
	 * @param treedata
	 * @param id
	 * @return
	 */
	private static Tree getTarget(List<Tree> treedata,String id){
		for(Tree node:treedata){
			String _id = node.getId();
			if(_id.equals(id))
				return node;
		}
		return null;
	}

 

 

你可能感兴趣的:(java)