JavaUtils - 반복 해석 다중 레벨 메뉴(데이터 트리)

3148 단어 JavaUtils

도구류

다중 메뉴 데이터: id, 부모 id, 하위 데이터 불러오는 집합
/**
 *  
 * @param 
 * @author jianda
 * @date 2017 5 26 
 */
public interface TreeEntity {
    public String getId();
    public String getParentId();
    public void setChildList(List childList);
}
/**
 *  
 * 
 * @author jianda
 * @date 2017 5 29 
 */
public class TreeParser{
    /**
     *  
     * @param topId
     * @param entityList
     * @return
     * @author jianda
     * @date 2017 5 29 
     */
    public static > List getTreeList(String topId, List entityList) {
        List resultList=new ArrayList<>();
        
        // 
        String parentId;
        for (E entity : entityList) {
            parentId=entity.getParentId();
            if(parentId==null||topId.equals(parentId)){
                resultList.add(entity);
            }
        }
        
        // 
        for (E entity : resultList) {
            entity.setChildList(getSubList(entity.getId(),entityList));
        }
        
        return resultList;
    }
    
    /**
     *  
     * @param id
     * @param entityList
     * @return
     * @author jianda
     * @date 2017 5 29 
     */
    private  static  >  List getSubList(String id, List entityList) {
        List childList=new ArrayList<>();
        String parentId;
        
        // 
        for (E entity : entityList) {
            parentId=entity.getParentId();
            if(id.equals(parentId)){
                childList.add(entity);
            }
        }
        
        // 
        for (E entity : childList) {
            entity.setChildList(getSubList(entity.getId(), entityList));
        }
        
        // 
        if(childList.size()==0){
            return null;
        }
        
        return childList;
    }
}

테스트

public class Menu implements TreeEntity{
    public String id;
    public String name;
    public String parentId;
    public List childList;
    //set、get ...
public class Test {
    public static void main(String[] args) {
        List list=new ArrayList<>();
        Menu menu1=new Menu();
        menu1.setId("1");
        menu1.setParentId("0");
        menu1.setName(" 1");
        list.add(menu1);
        
        Menu menu2=new Menu();
        menu2.setId("2");
        menu2.setParentId("0");
        menu2.setName(" 2");
        list.add(menu2);
        
        Menu menu3=new Menu();
        menu3.setId("3");
        menu3.setParentId("1");
        menu3.setName(" 11");
        list.add(menu3);
        
        Menu menu4=new Menu();
        menu4.setId("4");
        menu4.setParentId("3");
        menu4.setName(" 111");
        list.add(menu4);
        
        List    menus=TreeParser.getTreeList("0",list);
        System.out.println(menus);
    }
}

좋은 웹페이지 즐겨찾기