Update Value of Key in HashMap 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.

Output:

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:

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.

Output:

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:

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.

Output:

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:

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.

Output:

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:

The replace() method has another variant where we specify the old and new values and then update the Map by replacing them. The syntax :

Let us look at the implementation in the code.

Output:

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:

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.

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.

Output:

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.

Output:

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.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 29 November

    Create Array of Linked Lists in Java

    Table of ContentsIntroductionLinked List in JavaApplication of Array of Linked ListsCreate Array of Linked Lists in JavaUsing Object[] array of Linked Lists in JavaUsing the Linked List array in JavaUsing the ArrayList of Linked Lists in JavaUsing the Apache Commons Collections Package Introduction In this article, we will look at how to Create an Array […]

  • 20 September

    Return ArrayList in Java

    Table of ContentsReturn ArrayList in Java From a Static MethodReturn ArrayList in Java From a Non-static MethodConclusion This article discusses cases of returning an ArrayList in Java from a method. An ArrayList in Java is a collection of elements of the same data type under a single variable name. In different cases, you can return […]

  • 17 September

    Create List with One Element in Java

    Table of ContentsUsing Collections.singletonList()Using Array.asList() method [ Immuatable list]Using new ArrayList with Array.asList() method [ Mutable list] In this post, we will see how to create List with One Element in java.. Using Collections.singletonList() This is best way to create List with single element if you need an immutable List. [crayon-63b8031b1ce6e913121910/] Output [crayon-63b8031b1ce73499874023/] If you […]

  • 17 May

    How to Add Multiple Values for Single Key In HashMap in Java

    Table of ContentsHashMapCan HashMap Store Multiple Values AutomaticallyWays to Add Multiple Values for Single Key In HashMap in JavaUsing the Standard LibraryUsing Apache Commons LibraryUsing Google Guava LibraryUsing TreeSet as ValuesUsing a Wrapper ClassUsing Java TuplesUsing compute() Function in JDK 8Conclusion This article discusses the HashMap in Java and how to add multiple values for […]

  • java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
    22 February

    [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

    Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]

  • Java ArrayList of objects
    25 January

    Create ArrayList of Objects in Java

    Table of ContentsUsing the add() method to create ArrayList of objects in javaUsing parameterized constructor to create ArrayList of objects in javaUsing addAll() method to create ArrayList of objects in javaConclusion In this tutorial, we will learn how to create ArrayList of objects in Java. We will create a Book class with different properties and […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.