Skip to content
Advertisement

ResultSet to HashMap

I am trying to pass the output of a ResultSet to Java HashMap.

Map<Integer, String> sIDpNumberHashMap = new HashMap<Integer, String>();

while (DBresult.next()) {
    int sID = DBresult.getInt("slrid");         
    String pNumber = DBresult.getString("pNumber");
    sIDpNumberHashMap.put(sID , pNumber );
    System.out.println("Output1"+ sID + "t" + pNumber + "n");
}
System.out.println("Output2" + "n" + sIDpNumberHashMap);

While the Output1 is showing all the records(from the DB). The put command only takes the last value from the ResultSet in.

Output1:

 502332262  101E2571G103
 502332262  101E2571G103
 502332262  116E3139P001
 502332262  117E3640G025
 502332262  314B7159G003
 502332262  117E3640G025

Output2:

{502332262=117E3640G025}

How do I make the put command to iterate over the results from the ResultSet?

Advertisement

Answer

All your IDs are identical (502332262), and HashMap doesn’t allow duplicate keys. That’s the reason you see only one entry in the HashMap (containing the last value you put in the Map).

If you want to allow duplicates, consider a different collection to hold the data. For example, you can use an ArrayList<SomeClass> where SomeClass contains the two properties you read from the DB.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement