Open In App

How to Add or Update Elements in a HashTable in Java?

In Java, HashTable is a pre-defined class of the collection framework. It is a part of the java.util package and is used to store the key-value pairs in the program. In this article, we will learn how to add and update elements in a HashTable in Java.

Pre-defined Classe to add and update elements in a HashTable

To add or update elements in a HashTable the pre-defined class is:



Program to add and update elements in a HashTable in Java

Below is the code implementation to add or update elements in a HashTable.




// Java program to add or update elements in a HashTable
import java.util.Hashtable;
import java.util.Map;
  
public class GFGHashTableExample 
{
    public static void main(String[] args) 
    {
        // create a HashTable named as hashTable
        Hashtable<String, String> hashTable = new Hashtable<>();
  
        // adding elements
        hashTable.put("key1", "HTML");
        hashTable.put("key2", "CSS");
        hashTable.put("key3", "JavaScript");
        hashTable.put("key4", "ReactJs");
  
        // printing the elements before update
        System.out.println("Original HashMap");
        for (Map.Entry<String, String> entry : hashTable.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
  
        // updating an element
        hashTable.put("key3", "NodeJs");
  
        // Printing the elements after update
        System.out.println();
        System.out.println("Updated HashMap");
        for (Map.Entry<String, String> entry : hashTable.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output

Original HashMap
key4: ReactJs
key3: JavaScript
key2: CSS
key1: HTML

Updated HashMap
key4: ReactJs
key3: NodeJs
key2: CSS
key1: HTML

Explanation of the Program:


Article Tags :