Create a HashMap in Java Example

Java HashMap class implements the map interface by using a hash table. It inherits the AbstractMap class and implements the Map interface.

The important points about Java HashMap class:
  • A HashMap contains values based on the key.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.
  • Java HashMap is not thread-safe. You must explicitly synchronize concurrent modifications to the HashMap.

Create a HashMap in Java Example

The following example shows how to create a HashMap, and add new key-value pairs to it.

package com.javaguides.collections.hashmapexamples;

import java.util.HashMap;

import java.util.Map;

public class CreateHashMapExample {
    public static void main(String[] args) {
        // Creating a HashMap
     Map<String, Integer> numberMapping = new HashMap<>();

        // Adding key-value pairs to a HashMap
        numberMapping.put("One", 1);
        numberMapping.put("Two", 2);
        numberMapping.put("Three", 3);

        // Add a new key-value pair only if the key does not exist in the HashMap, or is mapped to `null`
        numberMapping.putIfAbsent("Four", 4);

        System.out.println(numberMapping);
        
    }
}

Output

{One=1, Four=4, Two=2, Three=3}

Reference

Comments