将从数据库查询出来的带有父子结构的list转换成treeList结构
阅读原文时间:2023年07月11日阅读:6

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DBHelper {
public static final String url = "jdbc:mysql://127.0.0.1/peixian";
public static final String name = "com.mysql.jdbc.Driver";
public static final String user = "root";
public static final String password = "root";

    public Connection conn = null;  
    public PreparedStatement pst = null;  

    public  DBHelper(String sql) {  
        try {  
            Class.forName(name);//指定连接类型  
            conn = DriverManager.getConnection(url,user,password);//获取连接  
            pst = conn.prepareStatement(sql);//准备执行语句  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

    public void close() {  
        try {  
            this.conn.close();  
            this.pst.close();  
        } catch (SQLException e) {  
            e.printStackTrace();  
        }  
    }

}
//调用demo类================
package test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mysql.jdbc.StringUtils;
public class Demo {
static String sql = null;
static DBHelper db1 = null;
static ResultSet ret = null;

public static void main(String\[\] args) {  
    sql = "select \*from xy\_sys\_menu";//SQL语句  
    db1 = new DBHelper(sql);//创建DBHelper对象

    try {  
        List<Map<String,Object>>list=new ArrayList<Map<String,Object>>();  
        ret = db1.pst.executeQuery();//执行语句,得到结果集  
        ResultSetMetaData md = ret.getMetaData(); //获得结果集结构信息,元数据  
        int columnCount = md.getColumnCount();   //获得列数  
        while (ret.next()) {  
            Map<String,Object> rowData = new HashMap<String,Object>();  
            for (int i = 1; i <= columnCount; i++) {  
                rowData.put(md.getColumnName(i), ret.getObject(i));  
            }  
            list.add(rowData);

        }  
        System.out.println("list============="+list);  
        List<Map<String, Object>>listTree=getTreeList("MENU\_NO","PMENU\_NO","children",list);  
        System.out.println("listTree===="+listTree);  
        ret.close();  
        db1.close();//关闭连接  
    } catch (SQLException e) {  
        e.printStackTrace();  
    }  
}

//把带有父子机构的数据变成treelist形式
public static List> getTreeList(String id,String pid,String children,List>list) {
//List>listmap=new ArrayList>();
//给list的每一项加一个子项
for(int i=0;i>());
}
List>treelist=new ArrayList>();
for(Map outmap:list) {
for(Map inmap:list) {
String outid=outmap.get(id).toString();
String inpid=inmap.get(pid).toString();
if(outid.equals(inpid)) {
List>maplist=(ArrayList) outmap.get(children);
maplist.add(inmap);
}
}
String prid=outmap.get(pid).toString();
if(StringUtils.isNullOrEmpty(prid)) {
treelist.add(outmap);
}
}
return treelist;
}
}