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
CodePudding user response:
You are adding your pair/list to your map collection on each iteration. What you want instead is to add your new values to your existing pair/list and only add it to your hashmap if it doesn't exist yet:
String gid, etype, orid = null;
HashMap<String, List<String>> map = new HashMap<>();
while (rs.next()) {
gid = rs.getString("gid");
etype = rs.getString("eType");
oid = rs.getString("Orid");
List<String> groupPairs = map.get(gid);
// check if the pair list for this group got initialized already
if(groupPairs == null) {
// pair list for this group doesn't exist yet, initializing and adding it to the HashMap
map.put(gid, new ArrayList<String>());
groupPairs = map.get(groupid);
}
// add the values of the current iteration to the corresponding pair list (within your HashMap)
groupPairs.add(entitytype);
groupPairs.add(orderid);
}
CodePudding user response:
If I understood the difference between the desired result and the result you're getting correctly, you need to reinstantiate pair
list 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.
while (rs.next()) {
List<String> pair = new ArrayList<String>();
// the rest code
}
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 groupId
can appear in the result set multiple times, you can use either putIfAbsent()
or Java 8 method computeIfAbsent()
in conjuction with Collections.addAll()
to update the map in a fluent and concise way.
computeIfAbsent()
:
while (rs.next()) {
List<String> pair = map.computeIfAbsent(rs.getString("gid"), k -> new ArrayList<>());
Collections.addAll(pair, rs.getString("eType"),rs.getString("Orid"));
}
putIfAbsent()
:
while (rs.next()) {
String groupId = rs.getString("gid");
map.putIfAbsent(groupId , new ArrayList<>());
List<String> pair = map.get(groupId);
Collections.addAll(pair, rs.getString("eType"),rs.getString("Orid"));
}