Java Program to Update value of HashMap using key

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to update value of HashMap using key. Java HashMap is a hash table based implementation of Java's Map interface. It is a collection of key-value pairs.

Below is a demonstration of the same −

Suppose our input is

Input HashMap: {Java=1, Scala=2, Python=3}

The desired output would be

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

Algorithm

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 – Create a hashmap of values and initialize elements in it using the ‘put’ method.
Step 5 - Display the hashmap on the console.
Step 6 - To fetch a specific value, access the hashmap using the key, with the ‘get’ method.
Step 7 - Add certain value to the fetched value.
Step 8 - Display the updated value on the console.
Step 9 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.HashMap;
public class Demo {
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      HashMap<String, Integer> input_map = new HashMap<>();
      input_map.put("Java", 1);
      input_map.put("Scala", 2);
      input_map.put("Python", 3);
      System.out.println("The HashMap is defined as: " + input_map);
      int value = input_map.get("Scala");
      value = value + 10;
      input_map.put("Scala", value);
      System.out.println("\nThe HashMap with the updated value is: " + input_map);
   }
}

Output

The required packages have been imported
The HashMap is defined as: {Java=1, Scala=2, Python=3}

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

import java.util.HashMap;
public class Demo {
   static void update(HashMap<String, Integer> input_map, String update_string){
      int value = input_map.get(update_string);
      value = value + 10;
      input_map.put("Scala", value);
      System.out.println("\nThe HashMap with the updated value is: " + input_map);
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      HashMap<String, Integer> input_map = new HashMap<>();
      input_map.put("Java", 1);
      input_map.put("Scala", 2);
      input_map.put("Python", 3);
      System.out.println("The HashMap is defined as: " + input_map);
      String update_string = "Scala";
      update(input_map, update_string);
   }
}

Output

The required packages have been imported
The HashMap is defined as: {Java=1, Scala=2, Python=3}

The HashMap with the updated value is: {Java=1, Scala=12, Python=3}
raja
Updated on 30-Mar-2022 10:34:53

Advertisements