Algorithm


  1. Initialize HashMap:

    • Create a HashMap instance.
  2. Insert Key-Value Pairs:

    • Add key-value pairs to the HashMap.
  3. Prompt for Key and New Value:

    • Take user input or set values for the key and the new value to be updated.
  4. Check if Key Exists:

    • Verify if the specified key exists in the HashMap.
  5. Update Value:

    • If the key is found, update the corresponding value with the new value.
  6. Print Updated HashMap:

    • Display the updated HashMap with the modified key-value pair.

 

Code Examples

#1 Code Example- Update value of HashMap using put()

Code - Java Programming

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);
  }
}
Copy The Code & Try With Live Editor

Output

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

#2 Code Example- Update value of HashMap using computeIfPresent()

Code - Java Programming

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);

  }
}
Copy The Code & Try With Live Editor

Output

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

#3 Code Example- Update value of Hashmap using merge()

Code - Java Programming

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);
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
HashMap: {Second=2, First=1}
HashMap with updated value: {Second=2, First=5}
Advertisements

Demonstration


Java Programing Example to Update value of HashMap using key-DevsEnv