Learn How to Use the Java HashMap Data Structure

A HashMap (or a HashTable) is a data structure that allows quick access to data using key-value pairs. The Java HashMap class extends the AbstractMap class and implements the Map interface, which gives it access to a lot of operations. HashMaps have two type parameters—K and V, where K stores the keys and V stores the values in each HashMap.

MAKEUSEOF VIDEO OF THE DAY

The HashMap allows you to map keys to a specific value and store items in random order. In this article, you will learn how to use Java’s HashMap class to store, retrieve, update, and delete data.

Creating a Java HashMap

The Java HashMap class has four constructors. The default constructor is the most popular one, it allows you to create an empty HashMap that will have a default capacity of 16.

import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> fruitsMap = new HashMap<Integer, String>();
}
}

The Java class above uses the default HashMap constructor to create a data structure called fruitsMap. The fruitsMap object will store data that has an integer key and a string value. However, since the HashMap class implements the Map interface, it can store a null value in either the key field, the value field, or both.


Storing Data in a HashMap

You can perform several operations using the HashMap class. The put(K key, V value) method is among its most popular methods, and it allows you to store data using a key-value pair, where each key maps to a value.

import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> fruitsMap = new HashMap<Integer, String>();
fruitsMap.put(3,"Pear");
fruitsMap.put(6,"Mango");
fruitsMap.put(7,"Plum");
fruitsMap.put(4,"Apple");
fruitsMap.put(1,"Orange");
fruitsMap.put(5,"Berries");
fruitsMap.put(2,"Melon");
}
}

The updated class above uses the put() method to add several fruits and their key to the existing fruitsMap data structure. It is important to note that the code above adds the data to the map randomly. This detail will become useful when you start reading the data from the HashMap.

Reading Data From a HashMap

There are several ways to read data from a HashMap. The method that you use will depend on how you want the data to look or even the type of data you want to retrieve.

Retrieve the HashMap Object

If you want to retrieve the data as an object, you can simply access the HashMap object, which in the example below is fruitsMap.


System.out.println(fruitsMap);

Adding the line of code above to the Main class, prints the following output in the console:

{1=Orange, 2=Melon, 3=Pear, 4=Apple, 5=Berries, 6=Mango, 7=Plum}

Though each value was randomly added to the HashMap, from the output you will see that HashMap stores the values in ascending order, based on the key assigned to each value. This is a feature that puts HashMaps ahead of other data structures such as the Array data structure that only support linear storage.

Retrieve All the Data Individually

If you want to retrieve all the data individually, then you can use the for method that allows you to traverse through the HashMap and print each value and its corresponding key. This method employs the Map interface that the HashMap class implements.


for (HashMap.Entry<Integer, String> fruit : fruitsMap.entrySet())
{
System.out.println("Key: " + fruit.getKey() + " Value: " + fruit.getValue());
}

Adding the method above to your code will print the following output in your console:

Key: 1 Value: Orange
Key: 2 Value: Melon
Key: 3 Value: Pear
Key: 4 Value: Apple
Key: 5 Value: Berries
Key: 6 Value: Mango
Key: 7 Value: Plum

Retrieve a Specific Value

The HashMap class has a get() method that takes a key and returns the value mapped to this key.


System.out.println(fruitsMap.get(4));

The line of code above prints the following output in the console:

Apple

Updating Data in a HashMap

After you create and populate a HashMap object, you can use the replace() method to update any item in the Map. The replace() method takes two or three arguments. The first replace() method takes the key associated with an existing item, along with the new value you want to map to it.


fruitsMap.replace(4, "Grapes");
System.out.print(fruitsMap);

Executing the code above prints the following object in the console:

{1=Orange, 2=Melon, 3=Pear, 4=Grapes, 5=Berries, 6=Mango, 7=Plum}

As you can see from the object above, “Grapes” maps to 4, which previously mapped to “Apple”.

The second replace() method takes the key associated with the existing item, the existing item, and the replacement value.


fruitsMap.replace(4, "Apple", "Grapes");
System.out.print(fruitsMap);

The code above prints the following object in the console:

{1=Orange, 2=Melon, 3=Pear, 4=Grapes, 5=Berries, 6=Mango, 7=Plum}

Deleting Data From a HashMap

You can either delete a specific item from your HashMap using the remove() method or delete all the data using the clear() method. The remove() method takes either one or two arguments. The first remove method takes the key associated with the value you want to remove:

 
fruitsMap.remove(5);
System.out.println(fruitsMap);

The code above prints the following object in the console:

{1=Orange, 2=Melon, 3=Pear, 4=Apple, 6=Mango, 7=Plum}

The updated object shows that the item with the key-value pair of 5 and “Berries” is no longer a part of the fruitsMap. The second remove() method takes a key and the value that it maps to.


fruitsMap.remove(5, "Berries");
System.out.println(fruitsMap);

The code above also prints the following object in the console:

{1=Orange, 2=Melon, 3=Pear, 4=Apple, 6=Mango, 7=Plum}

The clear() method takes no arguments and returns void.

fruitsMap.clear();
System.out.println(fruitsMap);

Executing the code above prints the following empty object in the console:

{}

Now You Can Perform CRUD Operations on a Java HashMap

HashMaps are one of several popular data structures that you need to know. This article teaches you how to perform CRUD operations on Java HashMaps. The HashMap is a very useful data structure, its main selling point is that it is one of the most efficient data structures, due to its access speed. However, it is also very convenient to use, as it allows random storage.

We use cookies to give you the best experience.