简体   繁体   中英

Need guidance with Hashmap and resultset

The resultset will return different set of data eg:

> Winter    1001    112 
> Summer    1001    112 
> Autumn    1001    110 
> Spring    1001    111
> Winter    1002    112 
> Summer    1002    116 
> Autumn    1002    110 
> Spring    1002    115
> Winter    1003    112 
> Autumn    1003    111 
> Spring    1003    115 
> Summer    1003    112

and the data i need to display is in this format:

I got data [winter,summer,Autumn,Spring] [data1] [112,112,110,111] [data2] [112,116,110,115] [data3][112,111,115,112]

I was writing the code and this is something what i have got

if (connection != null) {
                System.out.println("Got DB Connection!");
                String selectTableSQL = sql;
                Statement statement = connection.createStatement();
                ResultSet rs = statement.executeQuery(selectTableSQL);
                while (rs.next()) {
                    caltList.add("\""+rs.getString(1)+"\"");
                    dataList.add(rs.getString(3));
                }

                }

String result = "";
String gotData = "I got data "
result = String.format(res,gotData,caltList,dataList);

Can somebody guide with the Hashmap or some approach .. am new to java... and unable to proceed further

I think I would fill a LinkedHashMap<Integer, HashMap<String, Integer> with the data from the ResultSet in this way:

LinkedHashMap [
  => 1001
       => "Winter" => 112
       => "Summer" => 112
       => "Autumn" => 110
       => "Spring" => 111

  => 1002
       => "Winter" => 112
       => "Summer" => 116
       => "Autumn" => 110
       => "Spring" => 115
  => ...
]

Then in a second loop I would create the output which you expect from it. ( [winter,summer,Autumn,Spring] [data1] [112,112,110,111] [data2] [112,116,110,115] ...] ).

That's why I chose a LinkedHashMap because it keeps the order in which you add it's entries. So it is assured that data1 is the first entry in the Map and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM