HashMap put() Method Example

1. Introduction

The HashMap class in Java is a part of the Collections Framework, which implements the Map interface. It stores data in key-value pairs, making data retrieval efficient and straightforward by using keys. The put(K key, V value) method is a crucial method in the HashMap class. It is used to add a new key-value pair to the map or update the value of an existing key. If the map previously contained a mapping for the key, the old value is replaced by the specified value. This method is fundamental for manipulating the contents of a HashMap.

2. Program Steps

1. Create a HashMap.

2. Use the put method to add new key-value pairs to the map.

3. Use the put method again to update the value associated with an existing key.

4. Display the contents of the HashMap.

3. Code Program

import java.util.HashMap;

public class HashMapPutMethodExample {
    public static void main(String[] args) {
        // Step 1: Creating a HashMap
        HashMap<Integer, String> map = new HashMap<>();

        // Step 2: Adding key-value pairs to the HashMap
        map.put(1, "Ramesh");
        map.put(2, "Suresh");
        map.put(3, "Mahesh");

        // Displaying the initial contents of the HashMap
        System.out.println("Initial map: " + map);

        // Step 3: Updating the value for key 2
        map.put(2, "Dinesh");

        // Displaying the updated contents of the HashMap
        System.out.println("Updated map: " + map);
    }
}

Output:

Initial map: {1=Ramesh, 2=Suresh, 3=Mahesh}
Updated map: {1=Ramesh, 2=Dinesh, 3=Mahesh}

Explanation:

1. A new HashMap is created, intended to map Integer keys to String values.

2. The put method is used to insert three key-value pairs into the map. This step demonstrates adding new data to the map.

3. The value for an existing key (2) is updated by calling the put method again with the same key but a different value ("Dinesh" replaces "Suresh"). This illustrates how put can be used to update the value associated with a specific key.

4. The outputs before and after the update show the initial contents of the map and how they change after using put to update a value. The map automatically replaces the old value with the new one for the specified key, demonstrating the key-value pair's add and update functionality within a HashMap.

Comments