递归处理List集合【无限级分类的实现】

class Location {  
    private int id; //id  
    private String name; //名称  
    private int parentId; //父id  
    //为了组合多维集合添加的属性  
    private List<Location> list;
	//GetSet...
}  
public class T2 {
	
	public static void main(String[] args) {
		//一维
		List<Location> list = getChilds(data, 1);
		for(Location l : list){
			System.out.println(l.getName());
		}
		System.out.println("===============");
		//多维
		List<Location> list2 = getChildsManyGroup(data, 1);
		for(Location l : list2){
			System.out.println(l.getName());
			for(Location ll : l.getList()){
				System.out.println("\t"+ll.getName());
				for(Location lll : ll.getList()){
					System.out.println("\t\t"+lll.getName());
					for(Location lllL : lll.getList()){
						System.out.println("\t\t\t"+lllL.getName());
						
					}
				}
			}
		}
	}
	//查询数据库表中所有数据,(这里模拟一个表的所有数据)
	static List<Location> data = new ArrayList<Location>();  
    static{  
        //new Location(编号, "名称", 父编号);  
        Location l = new Location(1, "编程语言", 0);  
        Location l1 = new Location(2, "数据库", 0);  
        Location l2 = new Location(3, "Java", 1);  
        Location l3 = new Location(4, ".NET", 1);  
        Location l4 = new Location(5, "java EE", 3);  
        Location l5 = new Location(6, "java SE", 3);  
        Location l6 = new Location(7, "java ME", 3);  
        Location l7 = new Location(8, "asp.NET", 4);  
        Location l8 = new Location(9, "ado.NET", 4);  
        Location l9 = new Location(10, "MySQL", 2);  
        Location l10 = new Location(11, "Oracle", 2);  
        Location l11 = new Location(12, "hibernate", 5);  
        Location l12 = new Location(13, "hibernate 3.5", 12); 
        Location l13 = new Location(14, "hibernate 4.2", 12);
        data.add(l);data.add(l1);data.add(l2);  
        data.add(l3);data.add(l9);data.add(l10);  
        data.add(l4);data.add(l5);data.add(l6);data.add(l7);data.add(l8);data.add(l11);
        data.add(l12);data.add(l13);
    }  
    /** 
     * 根据id 获取所有父级目录 一维 
     * 用途(首页 > 编程语言 > JAVA >  hibernate > hibernate入门教程)类似这样的一个系统当前位置   传入位置获取到所有父级 
     * @param list 
     * @param pid 
     * @return 
     */  
    public static List<Location> getParents(List<Location> list,int pid){  
        List<Location> arr = new ArrayList<Location>();  
        for (Location location : list) {  
            if(pid == location.getId()){  
                arr.addAll(getParents(list, location.getParentId()));  
                arr.add(location);  break;
            }  
        }  
        return arr;  
    }  
    /**
     * 根据id获取所有子集分类(一维List集合)
     * 1 11 111
     * @param list
     * @param pid
     * @return
     */
    public static List<Location> getChilds(List<Location> list,int pid){
    	List<Location> arr = new ArrayList<Location>();
    	for(Location location : list){
    		if(pid == location.getParentId()){
    			arr.addAll(getChilds(list, location.getId()));
    			arr.add(location);
    			
    		}
    	}
    	return arr;
    }
    /**
     * 根据id返回所有子集分类,(多维List集合,List中含有子集List)
     * 
     *  1
     *    11
     *       111
     *  2
     *    22
     *       222 
     * @param list
     * @param pid
     * @return
     */
    public static List<Location> getChildsManyGroup(List<Location> list,int pid){
    	List<Location> arr = new ArrayList<Location>();
    	for(Location location : list){
    		if(pid == location.getParentId()){
    			location.setList(getChildsManyGroup(list, location.getId()));  
                arr.add(location); 
    		}
    	}
    	return arr;
    }
      
    /** 
     * 组合为一维集合 
     * @param list 
     * @param pid 
     * @return 
     */  
    public static List<Location> pushOneGroup(List<Location> list,int pid){  
        List<Location> arr = new ArrayList<Location>();  
        for (Location location : list) {  
            if(pid == location.getParentId()){  
                arr.add(location);  
                arr.addAll(pushOneGroup(list, location.getId()));  
            }  
        }  
        return arr;  
    }  
    /** 
     * 组合为多维集合 
     * 用途:系统首页的导航菜单,常见的2-3级通过下面的方法压栈成多维集合在供前台显示 
     * @param list 要便利的集合数据 
     * @param pid  父id 
     * @return 
     */  
    public static List<Location> pushManyGroup(List<Location> list,int pid){  
        List<Location> arr = new ArrayList<Location>();  
        for (Location location : list) {  
            if(pid == location.getParentId()){  
                location.setList(pushManyGroup(list, location.getId()));  
                arr.add(location);  
            }  
        }  
        return arr;  
    }  
      
}  


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
无限树(Java递归) 2007-02-08 10:26 这几天,用java写了一个无限极的树,递归写的,可能代码不够简洁,性能不够好,不过也算是练习,这几天再不断改进。前面几个小图标的判断,搞死我了。 package com.nickol.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.nickol.utility.DB; public class category extends HttpServlet { /** * The doGet method of the servlet. * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println(""); out.println(""); out.println(" Category" + "" + "body{font-size:12px;}" + "" + "" + ""); out.println(" "); out.println(showCategory(0,0,new ArrayList(),"0")); out.println(" "); out.println(""); out.flush(); out.close(); } public String showCategory(int i,int n,ArrayList frontIcon,String countCurrent){ int countChild = 0; n++; String webContent = new String(); ArrayList temp = new ArrayList(); try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(n==1){ if(rs.next()){ webContent += "";//插入结尾的减号 temp.add(new Integer(0)); } webContent += " ";//插入站点图标 webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,"0"); } if(n==2){ webContent += "\n"; }else{ webContent += "\n"; } while(rs.next()){ for(int k=0;k<frontIcon.size();k++){ int iconStatic = ((Integer)frontIcon.get(k)).intValue(); if(iconStatic == 0){ webContent += "";//插入空白 }else if(iconStatic == 1){ webContent += "";//插入竖线 } } if(rs.isLast()){ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(0)); }else{ webContent += "";//插入结尾的直角 } }else{ if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += "";//插入未结尾的减号 temp = (ArrayList)frontIcon.clone(); temp.add(new Integer(1)); }else{ webContent += "";//插入三叉线 } } if(checkChild(Integer.parseInt(rs.getString("cid")))){ webContent += " ";//插入文件夹图标 }else{ webContent += " ";//插入文件图标 } webContent += rs.getString("cname"); webContent += "\n"; webContent += showCategory(Integer.parseInt(rs.getString("cid")),n,temp,countCurrent+countChild); countChild++; } webContent += "\n"; DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return webContent; } public boolean checkChild(int i){ boolean child = false; try{ Connection conn = DB.GetConn(); PreparedStatement ps = DB.GetPs("select * from category where pid = ?", conn); ps.setInt(1, i); ResultSet rs = DB.GetRs(ps); if(rs.next()){ child = true; } DB.CloseRs(rs); DB.ClosePs(ps); DB.CloseConn(conn); }catch(Exception e){ e.printStackTrace(); } return child; } } --------------------------------------------------------------------- tree.js文件 function changeState(countCurrent,countChild){ var object = document.getElementById("level" + countCurrent + countChild); if(object.style.display=='none'){ object.style.display='block'; }else{ object.style.display='none'; } var cursor = document.getElementById("cursor" + countCurrent + countChild); if(cursor.src.indexOf("images/tree_minus.gif")>=0) {cursor.src="images/tree_plus.gif";} else if(cursor.src.indexOf("images/tree_minusbottom.gif")>=0) {cursor.src="images/tree_plusbottom.gif";} else if(cursor.src.indexOf("images/tree_plus.gif")>=0) {cursor.src="images/tree_minus.gif";} else {cursor.src="images/tree_minusbottom.gif";} var folder = document.getElementById("folder" + countCurrent + countChild); if(folder.src.indexOf("images/icon_folder_channel_normal.gif")>=0){ folder.src = "images/icon_folder_channel_open.gif"; }else{ folder.src = "images/icon_folder_channel_normal.gif"; }
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值