Table of Contents
- Using the put() Method of HashMap Collection in Java
- Using the compute() Method of HashMap Collection in Java
- Using the merge() Method of the HashMap Collection in Java
- Using the computeIfPresent() Method of The HashMap Collection in Java
- Using the replace() Method of The HashMap Collection in Java
- Using the TObjectIntHashMap Class of Gnu.Trove Package in Java
- Using the Atomic Integer class in Java
In this article, we will look at How to Update the Value of a Key in HashMap in Java. We will look at different solutions to this problem in detail with working examples.
It is recommended to learn about the concept of collections particularly HashMaps in Java and their working for a seamless understanding. Now, we outline different ways How to Update the Value of a Key in HashMap in Java. These approaches would also work for different maps like TreeMap, LinkedHashMap, etc.
Using the put() Method of HashMap Collection in Java
We can use the conventional put() method of HashMap collection to update a specific key. To use this method the key must be present within the HashMap but can also be modified for the default case.
Essential points :
- In a HashMap of Integer values, either directly put the value for a key or get the existing value for the key using the getKey() method and increment/decrement the value.
- If a key is not present and to avoid a Null-Pointer Exception use the getOrDefault() method to update the key, if it is not present assign a default value.
Let us look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.util.HashMap; public class UpdateHashMapKeyUsingPut { public static void main(String[] args) { //Create HashMap of String keys and Integer values. HashMap<String,Integer> hm = new HashMap<String,Integer>(); hm.put("Adam", 1); hm.put("Steve", 2); hm.put("James", 3); hm.put("Amanda", 4); hm.put("Carol", 5); System.out.println("HashMap before Update : "+hm); // Update key and assign new value. hm.put("James", 6); // Update key by incrementing its past value. hm.put("Steve",hm.get("Steve") + 1); // Update key with getOrDefault // Assigns default value : 7 if key is not present hm.put("Jones", hm.getOrDefault("Jones", 7)); // If key present increment original value by 1. hm.put("Carol", hm.getOrDefault("Carol", 7) + 1); System.out.println("HashMap after Update : "+hm); } } |
Output:
1 2 3 4 |
HashMap before Update : {Adam=1, Steve=2, James=3, Carol=5, Amanda=4} HashMap after Update : {Adam=1, Jones=7, Steve=3, James=6, Carol=6, Amanda=4} |
Using the compute() Method of HashMap Collection in Java
The HashMap collection provides the compute() method that is useful in computing the key and values of a HashMap based on a BiFunction. We will understand this with some examples.
The syntax of the method:
1 2 3 |
default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) |
The method commonly accepts two parameters:
- The Key to update.
- The Remapping function or BiFunction – To compute the value of the Key.
Example
The method declaration : compute(“John”, (key, value) -> value + 1)Â
- Gets the value of key “John” and updates the key by incrementing the original value by 1.
Similarly, the method declaration : compute(“John”, (key, value) -> (value == null) ? 1 : value + 1)Â
- Checks if the value of key “John” is present and assign a default value of 1Â if the key is absent.
Let us look at the implementation of these examples in code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.HashMap; public class UpdateHashMapKeyUsingCompute { public static void main(String[] args) { //Create HashMap of String keys and Integer values. HashMap<String,Integer> hm = new HashMap<String,Integer>(); hm.put("Adam", 1); hm.put("Steve", 2); hm.put("James", 3); hm.put("Amanda", 4); hm.put("Carol", 5); System.out.println("HashMap before Update : "+hm); // Remap value using compute() method. // If key is present increment value. hm.compute("James", (key,value) -> value + 1); // If key absent assigns a default value hm.compute("Angel", (key,value) -> (value == null) ? 1 : value + 1); System.out.println("HashMap after Update : "+hm); } } |
Output:
1 2 3 4 |
HashMap before Update : {Adam=1, Steve=2, James=3, Carol=5, Amanda=4} HashMap after Update : {Adam=1, Steve=2, James=4, Angel=1, Carol=5, Amanda=4} |
Using the merge() Method of the HashMap Collection in Java
The merge() method of HashMap is basically used to merge two HashMaps based on Mapping criteria. However, we can also use this to Update the Value of a Key in HashMap. We will understand with some examples.
The syntax of the method:
1 2 3 |
public V merge(K key, V value, BiFunction remappingFunction) |
The method accepts three parameters:
- Key to update.
- Value: Here, it corresponds to the default value for the key if absent.
- Re-Mapping or BiFunction: To compute the value of the key based on the rule and the default Value
Example:
The method declaration: merge((“Steve”, 2, (v1, v2) -> v1 + v2))
- Updates the value of the Key “Steve” with 4 as rule v1 + v2 with the default value of 2 gives result 4.
- If the Key is absent, it creates the Key “Steve” and assigns a default value of 2
Let us look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.HashMap; public class UpdateHashMapKeyUsingMerge { public static void main(String[] args) { //Create HashMap of String keys and Integer values. HashMap<String,Integer> hm = new HashMap<String,Integer>(); hm.put("Adam", 1); hm.put("Steve", 2); hm.put("James", 3); hm.put("Amanda", 4); hm.put("Carol", 5); System.out.println("HashMap before Update : "+hm); System.out.println(); // Remap value using merge() method. // If key is present calculate new value based on rule hm.merge("Steve", 2, (v1, v2) -> v1 + v2); // If key absent assign default value. hm.merge("Stark", 2, (v1, v2) -> v1 + v2); System.out.println("HashMap after Update : "+hm); } } |
Output:
1 2 3 4 5 |
HashMap before Update : {Adam=1, Steve=2, James=3, Carol=5, Amanda=4} HashMap after Update : {Adam=1, Steve=4, James=3, Carol=5, Stark=2, Amanda=4} |
Using the computeIfPresent() Method of The HashMap Collection in Java
The computeIfPresent() method of the HashMap follows the same resemblance to the compute() method in working aspects as discussed above. We can use it to Update the Value of a Key in HashMap. We will understand with some examples.
The syntax of the method:
1 2 3 |
public Object computeIfPresent(Object key, BiFunction remappingFunction) |
The computeIfPresent method() accepts the same parameters with their type as in the compute() method. The only catch is for this method to work the Key must be present within the HashMap.
Example
The method declaration : computeIfPresent(“John”, (key,value) -> value + 1)
- Updates the Key “John” only if it is present and increments the associated value by 1. If key is not present no update is done and no Errors/Exceptions are thrown.
Let us look at the code snippet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.util.HashMap; public class UpdateHashMapKeyUsingComputeIfPresent { public static void main(String[] args) { //Create HashMap of String keys and Integer values. HashMap<String,Integer> hm = new HashMap<String,Integer>(); hm.put("Adam", 1); hm.put("Steve", 2); hm.put("James", 3); hm.put("Amanda", 4); hm.put("Carol", 5); System.out.println("HashMap before Update : "+hm); System.out.println(); // Remap value using computeIfPresent() method. // Increments value by 2 only if key present hm.computeIfPresent("Steve", (key,value) -> value + 2); System.out.println("HashMap after Update : "+hm); } } |
Output:
1 2 3 4 5 |
HashMap before Update : {Adam=1, Steve=2, James=3, Carol=5, Amanda=4} HashMap after Update : {Adam=1, Steve=4, James=3, Carol=5, Amanda=4} |
Further reading:
Using the replace() Method of The HashMap Collection in Java
The replace() method of the Map interface implemented by the HashMap class is used to replace the value of a given key and Update the Key of the HashMap. The syntax of the method:
1 2 3 |
public V replace(K key, V value) |
The replace() method has another variant where we specify the old and new values and then update the Map by replacing them. The syntax :
1 2 3 |
public boolean replace(K key, V oldValue, V newValue) |
Let us look at the implementation in the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.HashMap; public class UpdateHashMapKeyUsingReplace { public static void main(String[] args) { //Create HashMap of String keys and Integer values. HashMap<String,String> hm = new HashMap<String,String>(); hm.put("Adam", "Computers"); hm.put("Steve", "Accounts"); hm.put("James", "Finance"); hm.put("Amanda", "Admin"); hm.put("Carol", "Finance"); System.out.println("HashMap before Update : "+hm); System.out.println(); // Direct replace value using replace() method hm.replace("Adam", "Developer"); // Updating key value by concating strings hm.replace("Carol", hm.get("Carol").concat(" & Computers")); // Specifying old and new values to Update hm.replace("James", "Accounts", "Finance"); System.out.println("HashMap after Update : "+hm); } } |
Output:
1 2 3 4 5 |
HashMap before Update : {Adam=Computers, Steve=Accounts, James=Finance, Carol=Finance, Amanda=Admin} HashMap after Update : {Adam=Developer, Steve=Accounts, James=Finance, Carol=Finance & Computers, Amanda=Admin} |
Using the TObjectIntHashMap Class of Gnu.Trove Package in Java
The gnu.trove package provides powerful and reusable components as dependencies that we can embed into our applications and programs. Here, to update the Value of a Key in HashMap we use the map library inbuilt functionality of this package library.
The Trove package provides the TObjectIntHashMap class which we will use in our examples. The HashMap is declared as follows:
1 2 3 4 5 6 7 |
// Map having keys of type String TObjectIntHashMap<String> hm = new TObjectIntHashMap<String>(); // Map having keys of type Integer TObjectIntHashMap<Integer> hm = new TObjectIntHashMap<Integer>(); |
Package Specification: gnu.trove.map.hash.TObjectIntHashMap
We specify only the Key Data type(String, Integer, Float, Object, etc) while declaring the Map, the Value Data type is by default the Integer type in TObjectIntHashMap
There are two ways we can update the key of a TObjectIntHashMap :
- Using
increment()
method of TObjectIntHashMap Class. - Using
put()
method of TObjectIntHashMap Class.
You can use the gnu.trove package and the inbuilt functionality in your Java application by importing with the following dependency.
1 2 3 4 5 6 7 |
<dependency> <groupId>gnu.trove</groupId> <artifactId>trove</artifactId> <version>3.0.3</version> </dependency> |
For ease, we use the JAR component of this package in our code which is available to download from here. Now, let us look into the steps:
- We will call the increment() method and provide the key as a parameter the value of which needs to be updated. The method by default increments the value by 1.
- We use the put() method and specify the key to update along with the value.
Note: Only Integer values are allowed as the value to be associated with each key while creating the Map.
Let us look at the implementation in the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import gnu.trove.map.hash.TObjectIntHashMap; public class UpdateHashMapKeyUsingTrove { public static void main(String[] args) { //Create HashMap of String keys. TObjectIntHashMap<String> hm = new TObjectIntHashMap<String>(); //Only Integer values to be provided. hm.put("Adam", 1); hm.put("Steve", 2); hm.put("James", 3); hm.put("Amanda", 4); hm.put("Carol", 5); System.out.println("HashMap before Update : "+hm); System.out.println(); // Increments value of key by 1. hm.increment("Adam"); // Updates value of key using put() method hm.put("Amanda", 10); System.out.println("HashMap after Update : "+hm); } } |
Output:
1 2 3 4 5 |
HashMap before Update : {Steve=2,Adam=1,Carol=5,James=3,Amanda=4} HashMap after Update : {Steve=2,Adam=2,Carol=5,James=3,Amanda=10} |
Using the Atomic Integer class in Java
The AtomicInteger class is present in java.util.concurrent package and is very useful in providing components for automatic operations on Integral values. Here, we will declare a HashMap having the Value field of type AtomicInteger.
Here we highlight 4 ways to update the value of a key in a HashMap using AtomicInteger class:
- Using
updateAndGet()
method. - Using
incrementAndGet()
method. - Using
addAndGet()
method. - Using
decrementAndGet()
method.
Now let us look into each method step by step.
- We call the updateAndGet() method with the key to be updated. It accepts an IntUnaryOperator function which we specify using a rule. Ex: hm.get(“John”).updateAndGet((value) -> value + 1) updates the value of Key “John” by adding 1 to it.
- We call the incrementAndGet() with a particular key that increments and updates the key’s value by 1.
- We call the addAndGet() method with the key to update and provide a number to add to the original value associated with the key.
- We call the decrementAndGet() with a particular key that by default decrements the key’s value by 1.
Let us look at the code for this approach as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import java.util.HashMap; import java.util.concurrent.atomic.AtomicInteger; public class UpdateHashMapKeyUsingAtomicInteger { public static void main(String[] args) { //Create HashMap of String keys and Atomic Integer Values. HashMap<String,AtomicInteger> hm = new HashMap<String,AtomicInteger>(); //Create AtomicInteger and instantiate with integral values. hm.put("Adam", new AtomicInteger(1)); hm.put("Steve", new AtomicInteger(2)); hm.put("James", new AtomicInteger(3)); hm.put("Amanda", new AtomicInteger(4)); System.out.println("HashMap before Update : "+hm); System.out.println(); // Update Key Value and add 10 to it. hm.get("Adam").updateAndGet((value) -> value + 10); //Increments value of key by 1 hm.get("Steve").incrementAndGet(); // Adds and updates 5 to the key value hm.get("James").addAndGet(5); //Decrements value of key by 1. hm.get("Amanda").decrementAndGet(); System.out.println("HashMap after Update : "+hm); } } |
Output:
1 2 3 4 5 |
HashMap before Update : {Adam=1, Steve=2, James=3, Amanda=4} HashMap after Update : {Adam=11, Steve=3, James=8, Amanda=3} |
That’s all for the article, we discussed 7 ways How to Update the Value of a Key in HashMap in java in great depth and detail with code and working examples. You can try these examples out in your Local IDE for a clear understanding.
Feel free to reach out to us for any queries/suggestions.