In this post, we will go through everything you need to know about using Java HashMap with examples.

In the subsequent post, we will also be looking into the internal functioning of a Java HashMap that will help clarify the concepts behind a HashMap.

1 – What is a HashMap?

Let’s first understand what a HashMap actually means.

A map is essentially a key-value pair where every value is mapped to a key. In the context of a HashMap instance, every key is unique and we can use it to access the corresponding value.

Below is a representation of a HashMap:

java hashmap example

Here, Key 1 points to Value 1, Key 2 to Value 3 and so on.

At this point, you might wonder why we needed this type of structure? We could have simply put everything in a list. Why even bother with something like a HashMap?

The answer is simple. Performance.

It takes linear time to find an element in an unsorted list. Even if we have a sorted list, we can still only achieve logarithmic i.e. O(log n) time complexity using binary search.

And this is where a HashMap helps us.

The time complexity of accessing and inserting an element in a HashMap is O(1) or constant. This provides a great advantage in writing efficient logic.

1.1 – Setup

Now that we understand the what and why of HashMap, let’s see it in action. To demonstrate things in a better manner, we will create a class named Book. This class will store the basic information of a Book.

class Book {
        private String bookName;
        private String authorName;
        private List<String> genres;

        public Book(String bookName, String authorName) {
            this.bookName = bookName;
            this.authorName = authorName;
        }

        public String getBookName() {
            return bookName;
        }

        public void setBookName(String bookName) {
            this.bookName = bookName;
        }

        public String getAuthorName() {
            return authorName;
        }

        public void setAuthorName(String authorName) {
            this.authorName = authorName;
        }

        public List<String> getGenres() {
            return genres;
        }

        public void setGenres(List<String> genres) {
            this.genres = genres;
        }
    }

1.2 – Put Method

In order to put an object in a HashMap, we need to instantiate a HashMap object. Next, we need to create Book instances and put them into the HashMap.

See below code for reference.

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

        Map<String, Book> booksByName = new HashMap<>();

        Book wayOfKings = new Book("Way of Kings", "Brandon Sanderson");
        Book theDragonReborn = new Book("The Dragon Reborn", "Robert Jordan");

        booksByName.put(wayOfKings.getBookName(), wayOfKings);
        booksByName.put(theDragonReborn.getBookName(), theDragonReborn);
    }
}

As you can see, we create two Book objects and insert them into the HashMap using the put() method. We use the bookName as the key and the Book itself as the value.

1.3 – Get Method

Now that we have placed two objects in HashMap, let’s see how we can access them.

Book newBook = booksByName.get("Way of Kings");

This will fetch the relevant Book object from the HashMap.

Question 1 – But what happens if the key we supply is not present in the HashMap?

Well, in that case a null value is returned.

Question 2 – What if we insert two values with the same key?

In that case, the last inserted value is stored. In other words, the Java HashMap put() method will simply overwrite the existing value.

Question 3 – What if we use null value as the key? Is that even possible?

Yes, it is possible. We can use null as the key. See below:

Book theNullBook = new Book("Neuromancer", "William Gibson");
booksByName.put(null, theNullBook);

We can even get the nullBook by using the below statement:

Book mysteryBook = booksByName.get(null);

1.4 – Remove a Value

We can also remove a mapping from the HashMap. See below:

booksByName.remove("The Dragon Reborn");

1.5 – Check Existence of Key or Value in Java HashMap

To check if a particular key is present in the HashMap, we can do something as below:

Boolean isWayOfKingsPresent = booksByName.containsKey("Way of Kings");

As we can see, this will return a boolean value of true if the key is present.

Instead of key, if we wish to check if a particular value is present, we can use the containsValue() method as below:

Boolean isWayOfKingsBookPresent = booksByName.containsValue(wayOfKings);

Basically, we pass the Book object we want to check for.

CAUTION – While the containsKey() and containsValue() methods look quite similar and in our example case both will return true, there is an important distinction between the two methods. The containsKey() method works in O(1) or constant time complexity. On the other hand, the containsValue() method has O(n) or linear time complexity. This is because it is necessary to loop over all the values in the case of containsValue().

1.6 – Iterating over a Java HashMap

In typical programming requirements, we often have a need of iterating over a bunch of values. The same is the case with HashMap.

We can iterate over the set of keys as below:

for (String key: booksByName.keySet()) {
    Book book = booksByName.get(key);
}

We can also iterate over the set of all key-value pairs as below:

for(Map.Entry<String, Book> entry: booksByName.entrySet()) {
     Book value = entry.getValue()
     String key = entry.getKey();
}

Lastly, we could also get all the values as an ArrayList as below. In case you do not know about ArrayList, please refer to this post.

List<Book> books = new ArrayList<>(booksByName.values());

2 – Java HashMap Key

In our example scenario, we used a String as the key for our booksByName HashMap. However, we can also use any other key such as another object.

The only requirement is that for the Map to work correctly, we need to provide an implementation of the equals() and hashCode().

See below example for our Book class.

@Override
public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return bookName.equals(book.bookName) && authorName.equals(book.authorName);
}

@Override
public int hashCode() {
        return Objects.hash(bookName, authorName)
}

Important note here is that the equals() and hashCode() need to be overridden only when we intend to use the object of a class as keys. No need to do the same when we only use them as values in a HashMap.

3 – Important Java8 Methods for Java HashMap

Java8 brought several functional-style methods to Java HashMap.

Let’s look at a few interesting methods that can make the life of a developer easier.

3.1 – The forEach() method

The forEach() method is a functional-style way to iterate over all elements in the map.

booksByName.forEach((key, book) -> {
       System.out.println("Key: " + key + " Book: " + book.getAuthorName());
});

3.2 – The getOrDefault() method

Using the getOrDefault() method, we can get a value from the map or return a default value in case there is no element for that particular key.

Book defaultBook = new Book("Default Book", "Default Author");
Book defaultExample = booksByName.getOrDefault("Fahrenheit 1984", defaultBook);

3.3 – The putIfAbsent() method

This method is very handy when we need to insert a new key-value pair only when the same key is not already present.

booksByName.putIfAbsent("Default Book", defaultBook);

With this, we have successfully explored Java HashMap and seen the usage of the most important methods available.

However, there is still a lot to know about HashMap and we will be doing so in the next post.

If you have any comments or queries, please feel free to mention in the comments section below.


Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *