I am using a loop statement to add keys and value in the map from a result set and if the key already exists, update that key and add to its value.
This is my code:
Map<Integer, Integer> item_id = new Hashmap<Integer , Integer>();
for (i=0 ; i<roomtype_id.length(); i++) {
String query ="SELECT item_id , quantity from amenities_tb where roomtype_id = '"+roomtype_id.get(i)+"'"
PreparedStatement pst = connection.preparedStatement(query);
Result Set rs = pst.executeQuery();
while(rs.next()) {
if (item_id.containskey(rs.getInt(1))) {
// update this key and add to its existing value
}
else {
item_id.put(rs.getInt(1),rs.getInt(2));
}
}
In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.
To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.
Change Dictionary Values in Python Using the dict. update() Method. In this method, we pass the new key-value pairs to the update() method of the dictionary object. We can change one and more key-value pairs using the dict.
In java 8 you can make the full if else just a single statement:
item_id.compute (rs.getInt (1), (key, old) -> (old == null ? 0 : old)+rs.getInt (2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With