Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add value to an existing key

Tags:

java

hashmap

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));
    }
  }
like image 561
STEPHEN YAO Avatar asked Jan 15 '16 15:01

STEPHEN YAO


People also ask

How do you add key-value pair to an existing dictionary?

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.

How do you add a value to an existing dictionary in Python?

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.

How do I change the value of a key in Python?

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.


1 Answers

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));
like image 95
Zbynek Vyskovsky - kvr000 Avatar answered Oct 10 '22 00:10

Zbynek Vyskovsky - kvr000