树节点工具

test

//从数据库查询出数据
List<ProductDirectory> result = productDirectoryDao.queryProductDir(productDirectory);
//转换成树形数据结构
List<ProductDirectory> treeList = TreeParser.getTreeList("0",result);
//

ProductDirectory

public class ProductDirectory implements TreeEntity<ProductDirectory>  {
	private static final long serialVersionUID = 1L;

	/**
	 * 主键
	 */
	private String id;

	private String releaseStatus;

	/**
	 * 名称
	 */
	private String name;

	/**
	 * 目录code
	 */
	private String directoryCode;

	/*HQ的目录id*/
        private String parentDirectoryCode;

        private  List<ProductDirectory>  childList;

TreeEntity

public interface TreeEntity<E> {

	public String getDirectoryCode();
	public String getParentDirectoryCode();
        public String getReleaseStatus();
	public void setChildList(List<E> childList);

}

TreeParser

**
 * 树形工具
 * @author znj
 *
 */
public class TreeParser {
    /**
     * 解析树形数据
     * @param topId
     * @param entityList
     * @return
     */
    public static <E extends TreeEntity<E>> List<E> getTreeList(String topId, List<E> entityList) {
        List<E> resultList=new ArrayList<>();
        //获取顶层元素集合
        String parentId;
        for (E entity : entityList) {
            parentId=entity.getParentDirectoryCode();
            if(parentId==null||topId.equals(parentId)){
                resultList.add(entity);
            }
        }
        //获取每个顶层元素的子数据集合
        for (E entity : resultList) {
            entity.setChildList(getSubList(entity.getDirectoryCode(),entityList));
        }
        return resultList;
    }
    
    /**
     * 获取子数据集合
     * @param id
     * @param entityList
     * @return
     */
    private  static  <E extends TreeEntity<E>>  List<E> getSubList(String id, List<E> entityList) {
        List<E> childList=new ArrayList<>();
        String parentId;
        //子集的直接子对象
        for (E entity : entityList) {
            parentId=entity.getParentDirectoryCode();
            if(id.equals(parentId)){
                  if(!entity.getReleaseStatus().equals("false")){
                    //子节点如果releaseStatus 是false 那就跳出
                    continue ;
                  }
                childList.add(entity);
            }
        }
        //子集的间接子对象
        for (E entity : childList) {
            entity.setChildList(getSubList(entity.getDirectoryCode(), entityList));
        }
        //递归退出条件
        if(childList.size()==0){
            return null;
        }
        return childList;
    }
}
上一篇:cocos2d-lua 按钮果冻效果


下一篇:Mybatis-plus 链式开发