I want to store the values in following way:
With every loop we are fetching different values for key, value1 & value2. Like this, MultiMap-> (key, value1, value2)
I used list for pairing value1 & value2 but with every loop values are getting added in list instead of getting in pairs. PSB code:
String gid, etype, orid = null;
HashMap<String, List<String>> map = new HashMap<>();
List<String> pair = new ArrayList<String>();
while (rs.next()) {
gid = rs.getString("gid");
etype = rs.getString("eType");
oid=rs.getString("Orid");
pair.add(entitytype);
pair.add(orderid);
map.put(groupid, pair);
}
i want output like:
key1, value1, value2 //loop1
key2, value1, value2 // loop2
instead i am getting:
key1, value1, value2 //loop1
key1, value1, value2, value1, value2 //loop2
If I understood the difference between the desired result and the result you're getting correctly, you need to reinstantiate
pairlist at every step of iteration over the result set instead of using the same list as the value of each entry.For that, you need to move the creation of the list into the body of the loop.
The fix suggested above would be sufficient if the keys retrieved by invoking
rs.getString("gid")are guaranteed to be unique.To caver the case make when the same
groupIdcan appear in the result set multiple times, you can use eitherputIfAbsent()or Java 8 methodcomputeIfAbsent()in conjuction withCollections.addAll()to update the map in a fluent and concise way.computeIfAbsent():putIfAbsent():