Java Utility Library

Java HashMap - put() Method



The java.util.HashMap.put() method is used to associate the specified value with the specified key in the map. If the key is already present in the map, the old value is replaced.

Syntax

public V put(K key, V value)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key with which the specified value is to be associated.
value Specify the value to be associated with the specified key.

Return Value

Returns previous value associated with given key, or null if there was no mapping for key.

Exception

NA

Example:

In the example below, the java.util.HashMap.put() method is used to associate key-value pairs in the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a hash map
    HashMap<Integer, String> MyMap = new HashMap<Integer, String>();

    //populating hash map
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");

    //printing hash map
    System.out.println("MyMap contains: " + MyMap);    

    //change a key-value pair
    MyMap.put(103, "Ramesh"); 

    //printing hash map
    System.out.println("MyMap contains: " + MyMap);  
  }
}

The output of the above code will be:

MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo}
MyMap contains: {101=John, 102=Marry, 103=Ramesh, 104=Jo}

❮ Java.util - HashMap