Java HashMap Collection Tutorial

In this Java tutorial we learn about the unordered HashMap collection that we can use to create collections of key:value pairs.

We learn about the required package to be imported, how to create, retrieve and delete elements.

We also discuss other HashMap methods that provide common functionality.

What is a HashMap

A HashMap is an unordered generic collection, similar to an ArrayList . However, instead of using numerical indeces, HashMaps allow us to specify key:value pairs.

We are allowed to have different types for our keys and values. For example, our keys can be of string type and our values of float type.

The HashMap class extends the AbstractMap class and implements the Map interface by using a hash table.

The HashMap package

Before we can work with HashMaps, we need to import its package.

Example:
 import java.util.HashMap;

Without the package, the compiler will raise an error when we try to instantiate a new HashMap.

How to create (instantiate) a HashMap in Java

A HashMap is a generic. We instantiate HashMaps the same way we do a generic class with two generic types.

The first generic type is the key type, the second is the value type.

Syntax:
HashMap<key_type_class, value_type_class> name = new HashMap<key_type_class, value_type_class>();

// or we can omit the second set of types
HashMap<key_type_class, value_type_class> name = new HashMap<>();

As with any other generic, we specify the type class wrapper instead of the primitive type. For example, we use Integer , not int .

Example:
// import appropriate package
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

        // instantiate new HashMap
        HashMap<String, String> country = new HashMap<String, String>();

        System.out.println(country);
    }
}

In the example above, we create a new HashMap called ‘country’ that has string keys and values.

How to add elements to a HashMap in Java

To add elements to a HashMap, we use the .put() method on the object. The method takes two arguments, first the key, then the value.

Syntax:
 hashmap_name.put(value);
Example:
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

        HashMap<String, String> country = new HashMap<String, String>();

        // add values to the HashMap
        country.put("AU", "Australia");
        country.put("DE", "Germany");
        country.put("US", "United States");
        country.put("UK", "United Kingdom");
        country.put("ZA", "South Africa");

        System.out.println(country);
    }
}

In the example above, we add several values to our HashMap. The keys are the abbreviations for the country names.

How to access single HashMap elements in Java

To access single elements in a HashMap we use the .get() method. The method takes the key of the element we want to access as an argument.

Syntax:
 hashmap_name.get(key);
Example:
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

        HashMap<String, String> country = new HashMap<String, String>();

        country.put("AU", "Australia");

        // get the value from 'AU' key
        System.out.println( country.get("AU") );
    }
}

In the example above, we get the value that’s associated with the ‘AU’ key.

How to access HashMap elements with a loop in Java

To access elements in a HashMap in a loop, we use the foreach (enhanced for) loop and the .keySet() or .values() methods.

The keySet method will retrieve the keys in the HashMap.

Example:
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

        HashMap<String, String> country = new HashMap<String, String>();

        country.put("AU", "Australia");
        country.put("DE", "Germany");
        country.put("US", "United States");
        country.put("UK", "United Kingdom");
        country.put("ZA", "South Africa");

        // access keys with keySet()
        for (String i: country.keySet()) {

            System.out.println(i);
        }
    }
}

The values method will retrieve the values in the HashMap.

Example:
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

        HashMap<String, String> country = new HashMap<String, String>();

        country.put("AU", "Australia");
        country.put("DE", "Germany");
        country.put("US", "United States");
        country.put("UK", "United Kingdom");
        country.put("ZA", "South Africa");

        // access values with values()
        for (String i: country.values()) {

            System.out.println(i);
        }
    }
}

To access both keys and values at once, we can use the keySet and get methods.

Example:
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

        HashMap<String, String> country = new HashMap<String, String>();

        country.put("AU", "Australia");
        country.put("DE", "Germany");
        country.put("US", "United States");
        country.put("UK", "United Kingdom");
        country.put("ZA", "South Africa");

        // access keys with keySet()
        // and values with get()
        for (String i: country.keySet()) {

            System.out.println("key: " + i + ", value: " + country.get(i));
        }
    }
}

How to remove single HashMap elements in Java

To remove a single element from an ArrayList, we use the .remove() method. The method takes the key of the element to be removed as an argument.

Syntax:
 hashmap_name.remove(key);
Example:
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

        HashMap<String, String> country = new HashMap<String, String>();

        country.put("AU", "Australia");
        country.put("DE", "Germany");
        country.put("US", "United States");
        country.put("UK", "United Kingdom");
        country.put("ZA", "South Africa");

        // remove element associated with 'AU'
        country.remove("AU");

        // access
        for (String i: country.keySet()) {

            System.out.println("key: " + i + ", value: " + country.get(i));
        }
    }
}

In the example above, we remove the element that’s associated with the ‘AU’ key. When we print the HashMap, the value doesn’t exist anymore.

How to remove all HashMap elements in Java

To remove all the elements from a HashMap at once, we use the .clear() method. The method takes not arguments.

Syntax:
 hashmap_name.clear();
Example:
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

        HashMap<String, String> country = new HashMap<String, String>();

        country.put("AU", "Australia");
        country.put("DE", "Germany");
        country.put("US", "United States");
        country.put("UK", "United Kingdom");
        country.put("ZA", "South Africa");

        // remove all elements in the HashMap
        country.clear();

        // try to access
        System.out.println(country);
    }
}

In the example above, we clear the HashMap of all its values. The HashMap still exists, it’s just empty.

When we try to print it to the console, the output only shows {}, indicating there are no values in the HashMap.

How to get the number of elements in a HashMap in Java

Java provides us with the .size() method to retrieve the number of elements in the HashMap. The method takes no arguments.

Syntax:
 hashmap_name.size();
Example:
import java.util.HashMap;

public class Program {
    public static void main(String[] args) {

        HashMap<String, String> country = new HashMap<String, String>();

        country.put("AU", "Australia");
        country.put("DE", "Germany");
        country.put("US", "United States");
        country.put("UK", "United Kingdom");
        country.put("ZA", "South Africa");

        // amount of elements in the HashMap
        System.out.println("Size: " + country.size());
    }
}

In the example above, we get the number of elements in the HashMap and print it to the console.

List of common HashMap methods in Java

Following is a list of more methods commonly used with ArrayLists.

MethodDescription
clone()Return a shallow copy of the specified HashMap.
containsKey()Evaluates if a specified key is found in the HashMap. Returns a boolean.
containsValue()Evaluates if a specified value is found in the HashMap. Returns a boolean.
void putAll()Copy all the elements of a HashMap to the another specified HashMap.

Summary: Points to remember

  • A HashMap is a generic collection that allows us to create a collection of key:value pairs.
  • A HashMap requires the java.util.HashMap package to be imported before we can use it.
  • A HashMap must be instantiated into an object and accepts its types as generic arguments between angle brackets.
  • We can add, retrieve and remove elements from the HashMap with the appropriate methods.
  • The clear method will remove all the elements from the HashMap. After the clearing, the HashMap still exists, it’s simply empty.
  • To get the length of a HashMap, we use the size method.