Java Program to Update value of HashMap using key

Java Program to Update value of HashMap using key

In this example, we will learn to update the value of the Java HashMap using key.

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Update value of HashMap using put()

import java.util.HashMap;

class Main {
  public static void main(String[] args) {

    HashMap<String, Integer> numbers = new HashMap<>();
    numbers.put("First", 1);
    numbers.put("Second", 2);
    numbers.put("Third", 3);
    System.out.println("HashMap: " + numbers);

    // return the value of key Second
    int value = numbers.get("Second");

    // update the value
    value = value * value;

    // insert the updated value to the HashMap
    numbers.put("Second", value);
    System.out.println("HashMap with updated value: " + numbers);
  }
}

Output

HashMap: {Second=2, Third=3, First=1}
HashMap with updated value: {Second=4, Third=3, First=1}

In the above example, we have used the HashMap put() method to update the value of the key Second. Here, first, we access the value using the HashMap get() method.


Example 2: Update value of HashMap using computeIfPresent()

import java.util.HashMap;

class Main {
  public static void main(String[] args) {

    HashMap<String, Integer> numbers = new HashMap<>();
    numbers.put("First", 1);
    numbers.put("Second", 2);
    System.out.println("HashMap: " + numbers);

    // update the value of Second
    // Using computeIfPresent()
    numbers.computeIfPresent("Second", (key, oldValue) -> oldValue * 2);
    System.out.println("HashMap with updated value: " + numbers);

  }
}

Output

HashMap: {Second=2, First=1}
HashMap with updated value: {Second=4, First=1}

In the above example, we have recomputed the value of the key Second using the computeIfPresent() method. To learn more, visit HashMap computeIfPresent().

Here, we have used the lambda expression as the method argument to the method.


Example 3: Update value of Hashmap using merge()

import java.util.HashMap;

class Main {
  public static void main(String[] args) {

    HashMap<String, Integer> numbers = new HashMap<>();
    numbers.put("First", 1);
    numbers.put("Second", 2);
    System.out.println("HashMap: " + numbers);

    // update the value of First
    // Using the merge() method
    numbers.merge("First", 4, (oldValue, newValue) -> oldValue + newValue);
    System.out.println("HashMap with updated value: " + numbers);
  }
}

Output

HashMap: {Second=2, First=1}
HashMap with updated value: {Second=2, First=5}

In the above example, the merge() method adds the old value and new value of the key First. And, insert the updated value to HashMap. To learn more, visit HashMap merge().