Java HashMap put()

The syntax of the put() method is:

hashmap.put(K key, V value)

Here, hashmap is an object of the HashMap class.


put() Parameters

The put() method takes two parameters:

  • key - the specified value is mapped with this key
  • value - the specified key is mapped with this value

put() Return Value

  • if key is already associated with any value, returns the previously associated value
  • if key is not associated with any value, returns null

Note: If key is previously associated with a null value, then also the method returns null.


Example 1: Java HashMap put()

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, Integer> languages = new HashMap<>();

    // insert items to the HashMap
    languages.put("Java", 14);
    languages.put("Python", 3);
    languages.put("JavaScript", 1);

    // display the HashMap
    System.out.println("Programming Languages: " + languages);
    }
}

Output

Programming Languages: {Java=14, JavaScript=1, Python=3}

In the above example, we have created a HashMap named languages. Here, the put() method inserts the key/value mappings to the hashmap.

Note: Every item is inserted in random positions in the HashMap.


Example 2: Insert Item with Duplicate Key

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, String> countries = new HashMap<>();

    // insert items to the HashMap
    countries.put("Washington", "America");
    countries.put("Ottawa", "Canada");
    countries.put("Kathmandu", "Nepal");
    System.out.println("Countries: " + countries);

    // add element with duplicate key
    String value = countries.put("Washington", "USA");
    System.out.println("Updated Countries: " + countries);

    // display the replaced value
    System.out.println("Replaced Value: " + value);
    }
}

Output

Countries: {Kathmandu=Nepal, Ottawa=Canada, Washington=America}
Updated Countries: {Kathmandu=Nepal, Ottawa=Canada, Washington=USA}
Replaced Value: America

In the above example, we have used the put() method to insert items to the hashmap. Notice the line,

countries.put("Washington", "USA");

Here, the key Washington is already present in the hashmap. Hence, the put() method replaces the previous value America with the new value USA.

Note: Till now, we have only added a single item. However, we can also add multiple items from Map to a hashmap using the Java HashMap putAll() method.

Did you find this article helpful?