HashMap in Java: What You Need to Know


HashMap in Java: What You Need to Know

Key Points

  • A hashmap in Java is a data structure that maps keys to values, providing efficient retrieval even for large datasets.
  • To use a hashmap in Java, you need to call the HashMap class and specify the types of data used for the keys and values.
  • Important methods for hashmaps in Java include hashCode, which allows you to specify how the hash is calculated, and equals, which defines how to compare two objects of the same class.

In Java, HashMaps are important data structures that can make a variety of tasks more efficient. When used, they allow a programmer to relate values in “key-value pairs,” where one element is used as an index, and another is retrieved using that index.

Here, we will go over what a HashMap is, how it can be used, and some important methods. Let’s dive in!

What Is a HashMap in Java?

hashmap in java
The above example initializes a HashMap called ages that maps names to ages. It demonstrates how to add entries, retrieve values based on keys, check if keys are present in the map, and remove entries.


To put it simply, a hash map is a data structure that maps keys to values. It sounds like nothing special, but the way that it does this is very efficient, making it a great solution even for large datasets.

Internally, an array is used, and values are hashed, turning them into an index in the array. The hash function essentially turns a longer string into a shorter one, through a process known as hashing. That being said, these nitty gritty details are unimportant to how you actually use them.

To use a HashMap in Java, you just need to call the HashMap class. Let’s go over how to do that.

How Do You Use a HashMap in Java?

If you want to use a HashMap in a program, you must import it at the top of the Java file. You can do this by typing:

import java.util.HashMap;

Suppose we want to relate a person’s name with their age. Let’s make a HashMap with Strings as keys and Integers as the values:

HashMap<String, Integer> ages = new HashMap<>();

If you haven’t seen it before, the syntax using angle brackets is known as generics in Java. Essentially, it allows you to specify the types of data used for the keys and values, but they are common in many other places.

By doing this, data does not have to be cast to be used. Note that primitive types cannot be used here, so we use Integer instead of int.

Now, let’s add a value to the HashMap. This can be done using the put method:

ages.put("Bob", 30);

If we want to retrieve the value later on, we can use the get method:

int bobAge = ages.get("Bob");

There are a few other things we can do. We can check if a key exists in a HashMap by using containsKey:

boolean hasBob = ages.containsKey("Bob");

And we can remove a key by using remove:


Important Methods


Any class can be specified for the keys of a HashMap in Java, and as aforementioned, they are reduced to an index in an array based on their hash. However, you can specify how that hash is calculated. As an example, here’s a class that represents a person:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;

    public String getName() {
        return name;

    public int getAge() {
        return age;

If we want to manually calculate the hash for a person object, here’s how we can do it:

    public int hashCode() {
        int result = name.hashCode() + age;
        return result;

Note that since hashCode and equals are methods of Object, which is automatically the superclass for Person, it is best to use @Override. To calculate the hash, we use the hash of the name, which is a string and already has an implementation for it, and we simply add the age of the person.


While this does stray a bit from HashMap, it is important to talk about the equals method if we mention hashCode. Often, if we want to compare two values, we simply use the == operator. However, if you do this with two objects, this simply compares their memory addresses, which is often not what we want.

Instead, we can implement the class’s equals method. This defines how to compare two objects of the same class. Here’s how we can do this with the Person class:

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        Person person = (Person) obj;
        return age == person.age && name.equals(person.name);

At the beginning, we cover some edge cases. If the objects have the same memory address, then they are obviously equal. However, if the given object is null, or they are not of the same class, they are not equal. After this, we simply check if the ages and names are the same, and we return true if so.

Why are we talking about this? Earlier, we talked about overriding the hashCode method, and if you are going to do so, you should always implement the equals method as well, as they are closely connected.

HashMap in Java: Wrapping Up

Although not always necessary, HashMaps are fundamental structures, and they can greatly reduce the complexity of a program. There is much more you can learn about them, and doing so will improve your skills as a Java developer.

Frequently Asked Questions

When would you use a hashmap in Java?

You can use a hashmap whenever you want to store key-value pairs. If you have data you want to store or group by a set of attributes, a hashmap can come in handy.

How does a hashmap handle collisions?

When two keys hash to the same index, this creates a collision. Java’s HashMap handles this by using a linked list for each bucket. When a collision occurs, a new key-value pair is simply added as a new node to the list. Since this can degrade performance, since Java 8, you can also use a balanced tree to handle hashmap collisions.

How does a HashMap handle null keys and values?

In Java’s HashMap, you can store one null key and multiple null values. The null key is stored at the 0th bucket, and the hash function is not used in this case.

To top