Dhanesh Khurana
Dhanesh Khurana

Reputation: 159

Updating HashMap in java

Do I need to remove value and then add or can I directly add it in HashMap and it will efficiently updated ? i.e.

HashMap<String, String> person = new HashMap<String, String>();
person.add("name", "John");

now which would be a better/efficient way to update above key value :

a)

person.remove("name");
person.add("name", "jamy");

b)

person.add("name", "jamy");

or are both just the same ?

This is a very small example. Considering a large HashMap containing other HashMaps, which would be better option and is there any even more efficient way to do so ?

Upvotes: 1

Views: 586

Answers (3)

Nisheeth Shah
Nisheeth Shah

Reputation: 608

java.util.HashMap provides put method to add key and object pair in the map. You do not have to remove the object if you want to update the HashMap object. It will return the previous object if there is any object in the map with the same key. Otherwise, it will simply return null. You do not have to remove it every time. Just use

java.util.HashMap.put(key, object);

Upvotes: 0

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

You can put the new value. It will substitute the old one. From javadoc:

If the map previously contained a mapping for the key, the old value is replaced.

Note that the method is put, not add. add is not a method of Hashmap

Edited: I added the reference link to the documentation as Naman Gala commented.

Upvotes: 2

Kanti
Kanti

Reputation: 1082

Use put method, as it will replace value for given key if key exist , otherwise it will create new entry

Upvotes: 0

Related Questions