What is a Java HashMap and how to use it

The HashMap class in Java lets you save data in key-value pairs. This not only makes it easier to retrieve and manage a list, but it also provides you with numerous access options. We’ll go over the most important methods here.

What are HashMaps in Java?

There are various ways to store and retrieve data. Which type of storage works best depends on how you intend to use the data. In many cases, the Java HashMap class is probably the best solution. Unlike other methods, this class stores data as key-value pairs. This means that each key is assigned exactly one value. If you want to retrieve a value, you can use the corresponding key to get the result you are looking for. Keys and values may consist of completely different data types including strings, numbers or other objects.

The Java HashMap class offers several advantages. The first being that you can perform a quick search within the programming language. The key-value approach also ensures that multiple values aren’t assigned to one key, preventing duplications. You can, however, add the same object several times using different keys. This type of storage and search functionality has a positive effect on performance when compared to rigid lists, which are significantly less flexible. This is also one of the major advantages of key-value stores, which use the same principle. In the following sections, we’ll show you how to create and use Java HashMaps.

Web Hosting
Fast, scalable hosting for any website
  • 99.9% uptime
  • PHP 8.3 with JIT compiler
  • SSL, DDoS protection, and backups

How to create and use HashMaps in Java

To create a new HashMap in Java, you need to import the class first. To do this, use the Java command import. The code looks like this:

import java.util.HashMap;
HashMap<String, String> nameOfTheHashMap = new HashMap<String, String> ();
java

The two data types, which are separated by a comma (in this case, String, String), are the key and the value.

Creating a new HashMap

To better explain how Java HashMaps work, we’ve come up with a simple example. For our example, we have a list of customers that a company wants to store and be able to access at any time. The list includes each customer’s name and a unique customer number. Although the customer number (the key in our example) is always unique, it’s possible for multiple customers to share the same name. Each of these customers, however, has their own unique number. This number is recorded as an integer data type, and the names as strings. Here’s how to set this up in a Java HashMap:

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

Adding elements

Now we have the Java HashMap, but it’s still empty. To add new key-value pairs, we are going to use the put() method. Here’s how it works:

public class Main {
public static void main(String[] args) {
	HashMap<Integer, String> customerList = new HashMap<>();
	customerList.put (1077, "Jerry Mowry");
	customerList.put (15312, "Peter Smith");
	customerList.put (73329, "Maria Grosso");
	System.out.println(customerList);
	}
}
java

We use the command System.out.println to display our customer list. The output should look like this:

{1077=Jerry Mowry, 15312=Peter Smith, 73329=Maria Grosso}
java

Retrieving elements

Now we’ve set up a customer list that can contain numerous entries. We also want to be able to access each customer entry individually. To do this, we pass the key to the get() method. Here is an example of how this works:

public class Main {
public static void main(String[] args) {
	HashMap<Integer, String> customerList = new HashMap<>();
	customerList.put (1077, "Jerry Mowry");
	customerList.put (15312, "Peter Smith");
	customerList.put (73329, "Maria Grosso");
	System.out.println(customerList.get(1077));
	}
}
java

Only the name “Jerry Mowry” should appear.

Deleting entries

If you want to get rid of an entry, use the remove() method. Here’s an example of how to use this method:

public class Main {
public static void main(String[] args) {
	HashMap<Integer, String> customerList = new HashMap<>();
	customerList.put (1077, "Jerry Mowry");
	customerList.put (15312, "Peter Smith");
	customerList.put (73329, "Maria Grosso");
	customerList.remove(1077);
	System.out.println(customerList);
	}
}
java

The output now looks like this:

{15312=Peter Smith, 73329=Maria Grosso}
java

Another option is to delete the entire list. To do this, use the clear() method.

public class Main {
public static void main(String[] args) {
	HashMap<Integer, String> customerList = new HashMap<>();
	customerList.put (1077, "Jerry Mowry");
	customerList.put (15312, "Peter Smith");
	customerList.put (73329, "Maria Grosso");
	customerList.clear();
	System.out.println(customerList);
	}
}
java

Now, the only output we get is this:

{ }
java

How to determine the number of entries

While our Java HashMap is quite simple, you can also use this class to manage larger, more complex projects as well. With a larger project, you may want to determine the exact number of entries you have. After all, this would be your entire customer base. You can use size() to do this. Here’s how:

public class Main {
public static void main(String[] args) {
	HashMap<Integer, String> customerList = new HashMap<>();
	customerList.put (1077, "Jerry Mowry");
	customerList.put (15312, "Peter Smith");
	customerList.put (73329, "Maria Grosso");
	System.out.println(customerList.size());
	}
}
java

In our example, the number 3 is output.

How to display only keys or values

You can also obtain a list that includes only the keys or the values, using a for-each loop. To retrieve keys, use the keySet() method, and for values, use the values() method. In the following code example, we’ll use values():

public class Main {
public static void main(String[] args) {
	HashMap<Integer, String> customerList = new HashMap<>();
	customerList.put (1077, "Jerry Mowry");
	customerList.put (15312, "Peter Smith");
	customerList.put (73329, "Maria Grosso");
	for (String i : customerList.values()) {
		System.out.println(i);
		}
	}
}
java

The output is:

Jerry Mowry
Peter Smith
Maria Grosso
java

Checking if a HashMap contains a specific value or key

In addition to accessing a specific entry, you can also check whether an entry already exists in a Java HashMap. You can do this by using the method containsKey() (for keys) and the method containsValue() (for values). If the element is included, the output will be “true.” If the element is not in the HashMap, the output will be “false.” Here’s how both methods work:

public class Main {
public static void main(String[] args) {
	HashMap<Integer, String> customerList = new HashMap<>();
	customerList.put (1077, "Jerry Mowry");
	customerList.put (15312, "Peter Smith");
	customerList.put (73329, "Maria Grosso");
	System.out.println(customerList.containsKey(15312));
	System.out.println(customerList.containsValue("Stuart Miller");
	}
}
java

Since the key “15312” is included, but the value “Stuart Miller” isn’t, the output looks like this.

true
false
java
Was this article helpful?
We use cookies on our website to provide you with the best possible user experience. By continuing to use our website or services, you agree to their use. More Information.
Page top