Write a Java Program to Update value of HashMap using key

Write a Java Program to Update value of HashMap using key

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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);
  }
}

Final output

Leave a Comment