无限级树数据结构构造

目前做机构管理这块,需要构造无限级树代码。

根节点为null,传进来数据集 List

构造根节点:

List<SysOrgBean> retList = new ArrayList<SysOrgBean>();
		for (SysOrgBean bean : beanList) {
			if(StringUtil.isEmpty(bean.getParentOrgId())){
				List<SysOrgBean> children = getChildren(beanList,bean.getOrgId());
				if(null != children && !children.isEmpty()){
					bean.setChildren(children);
					for (SysOrgBean sysOrgBean : children) {
						buildNode(sysOrgBean, beanList);
					}
				}
				retList.add(bean);
			}
		}
		return retList;

getChildren获取节点子集,buildNode构造子节点。

public static void buildNode(SysOrgBean sysOrgBean, List<SysOrgBean> beanList){
	List<SysOrgBean> children = getChildren(beanList, sysOrgBean.getOrgId());
		if (null != children && !children.isEmpty()) {  
		sysOrgBean.setChildren(children);  
            for (SysOrgBean child : children) {
                buildNode(child, beanList);
            }  
        }
}
public static List<SysOrgBean> getChildren(List<SysOrgBean> beanList, String parentOrgId){
	List<SysOrgBean> childList = new ArrayList<SysOrgBean>();
	for (SysOrgBean sysOrgBean : beanList) {
		if(!StringUtil.isEmpty(sysOrgBean.getParentOrgId()) && sysOrgBean.getParentOrgId().equals(parentOrgId)){
			childList.add(sysOrgBean);
			//beanList.remove(sysOrgBean);
		}
	}
	return childList;
}

由于用hibernate,需要将数据实体转换称业务实体,够造如下方法:

public static List<SysOrgBean> parse(List<SysOrg> orgList){
		List<SysOrgBean> beanList = null;  
        if(null != orgList && !orgList.isEmpty()){  
        	beanList = new ArrayList<SysOrgBean>();  
            for(SysOrg org : orgList){
            	SysOrgBean bean = parse(org);  
                if(null != bean){  
                	beanList.add(bean);  
                }  
            }  
        }  
        return beanList;  
	}
	
	public static SysOrgBean parse(SysOrg org){
		if(org != null){
			SysOrgBean orgBean = new SysOrgBean();
			orgBean.setOrgId(org.getOrgId());
			orgBean.setParentOrgId(org.getParentOrgId());
			orgBean.setOrgName(org.getOrgName());
			orgBean.setOrgLevel(org.getOrgLevel());
			orgBean.setSortNo(org.getSortNo());
			return orgBean;
		}
		return null;
	}

相关推荐