将结果集转换为地图

Convert Resultset into Map

我有一个查询return 两个值(A 列和 B 列)如下

A        B
------------
a   aaa
a   aaa
a   aaa
a   aaa
b   bbb
c   ccc
c   ccc
b   bbb
c   ccc
b   bbb

我正在尝试创建一个 java 方法(Java 7),它将一次性获取所有这些值并将其存储在集合变量(Map)中,就像以下格式

(a -> (aaa,aaa,aaa,aaa,aaa),
 b -> (bbb,bbb,bbb),
 c -> (ccc,ccc,ccc))

以下是我正在尝试的方法,但我什至无法首先获取所有数据:

import java.sql.*;
import java.util.ArrayList;

public class CollectionFrame {


    public static void main(String[] args) {

        try {
            // step1 load the driver class
            Class.forName("oracle.jdbc.driver.OracleDriver");

            // step2 create the connection object
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");

            // step3 create the statement object
            Statement stmt = con.createStatement();

            // step4 execute query

            // Lists of Lists to store the values
            ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
            ArrayList<String> obj = new ArrayList<String>();

            ResultSet rs = stmt.executeQuery("select * from t");
            while (rs.next()) {
                // System.out.println(rs.getString(1) + " " + rs.getString(2));
                obj.add(rs.getString(1));
                // obj.add(rs.getString(2));
                listOLists.add(obj);
                obj.removeAll(obj);

            }

            // step5 close the connection object
            con.close();

            System.out.println(listOLists.toString());

        } catch (Exception e) {
            System.out.println(e);
        }

    }

}

上面的代码给出了下面的结果

[[a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b], [a, a, a, a, b, c, c, b, c, b]]

如果我取消注释 obj.removeAll(obj); 行,我会得到以下信息:

[[], [], [], [], [], [], [], [], [], []]

我被困在这里了。有人可以帮助我如何进行或提出更好的解决方案吗?

你应该为此使用地图。

ResultSet rs = stmt.executeQuery("select * from t");
Map<String, List<String>> valueMap = new HashMap<>();

while (rs.next()) {
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);
    
    valueMap.putIfAbsent(columnAstring, new ArrayList<>());
    valueMap.get(columnAstring).add(columnBstring);
   
}

编辑:所以 putifabsent 可能效率很低,因为我将创建和丢弃大量数组列表。正如@Andreas 所指出的。所以这会稍微不那么干净,但更有效的方法!

兼容JAVA7

ResultSet rs = stmt.executeQuery("select * from t");
Map<String, List<String>> valueMap = new HashMap<>();

while (rs.next()) {
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);
    
    if(!valueMap.containsKey(columnAstring)){
        valueMap.put(columnAstring, new ArrayList());
    }
    valueMao.get(columnA).add(columnBstring);
   
}

使用 Java 8 个 Lambdas

@Mureinik's has pointed out an even cleaner way using computeIfAbsent.

while (rs.next()) {
    String columnAstring = rs.getString(1);
    String columnBstring = rs.getString(2);
    
    valueMap.computeIfAbsent(columnAstring, k -> new ArrayList<>())
    valueMap.get(columnAstring).add(columnBstring);
}

我将遍历 ResultSet 并将更改应用到地图 Map<String, List<String>>。在每次迭代中,如果键(A 列)不存在,您需要使用一个空列表添加它,然后一旦您确定您有该键的列表,就附加 B 列中的值。幸运的是, Java 8 对 Map 界面的改进使其非常优雅:

Map<String, List<String>> result = new HashMap<>();
while (rs.next()) {
    String a = rs.getString("a");
    String b = rs.getString("b");

    result.computeIfAbsent(a, k -> new ArrayList<>()).add(b);
}

也许你可以试试这个。这使用了 HashMap。

public class Main {
public static void main(String[] args) {

    //sample CSV strings...pretend they came from a file
    String[] csvStrings = new String[] {
      "a aaa","a aaa","a aaa","a aaa","b bbb","b bbb","b bbb",
      "b bbb","c ccc","c ccc","c ccc"
    };

    List<List<String>> csvList = new ArrayList<List<String>>();
    Map<String,ArrayList<String>> outVal 
        = new HashMap<String, ArrayList<String>>();

    for(String val:csvStrings){
        String outList[] = val.split(" ");
        if (outVal.containsKey(outList[0])){
            outVal.get(outList[0]).add(outList[1]);
        } else {
            ArrayList<String> inputList = new ArrayList<String>();
            inputList.add(outList[1]);
            outVal.put(outList[0],inputList);
        }
    }

   System.out.println(outVal.toString());  
}

}

这是输出: {a=[aaa, aaa, aaa, aaa], b=[bbb, bbb, bbb, bbb], c=[ccc, ccc, ccc]}