Back to Java
2026-02-125 min read

Java HashMap

Learn Java HashMap step by step with clear examples and exercises.

Why This Matters

Welcome to this full guide on Java HashMap! In this tutorial, we will delve into understanding what a HashMap is, its importance in Java programming, and how to use it effectively. We'll also cover common mistakes, practice questions, and frequently asked questions to help you master this essential data structure.

Why This Matters

In Java, the HashMap is an implementation of the Map interface that allows storing key-value pairs in a hash table. The HashMap provides fast access to its elements due to its efficient hashing mechanism. Understanding and using HashMap effectively can help you write more efficient code, especially when dealing with large datasets or complex data structures.

Prerequisites

Before diving into the core concept of Java HashMap, it's essential that you have a good understanding of the following:

  • Basic Java syntax and programming constructs (variables, loops, methods)
  • Interfaces and classes in Java
  • Data structures like arrays and linked lists
  • Exception handling in Java
  • Understanding of abstract data types (ADT) and their implementations

Core Concept

What is a HashMap?

A HashMap is a collection that maps keys to values. Each key can only map to one value, but multiple keys can map to the same value if needed. The HashMap uses a hash table internally to store its elements, which provides fast access to the stored data.

Creating a HashMap

To create a new HashMap in Java, you can use the following syntax:

HashMap<KeyType, ValueType> mapName = new HashMap<>();

Replace KeyType and ValueType with the actual data types you want to use for keys and values. For example:

Map<String, Integer> myMap = new HashMap<>();

Adding Elements to a HashMap

To add elements to a HashMap, you can use the put() method. This method takes two arguments – the key and the value you want to store. Here's an example:

myMap.put("Apple", 10);
myMap.put("Banana", 5);
myMap.put("Orange", 7);

Accessing Elements from a HashMap

To access the value associated with a key in a HashMap, you can use the get() method:

int bananas = myMap.get("Banana"); // returns 5

Removing Elements from a HashMap

To remove an element from a HashMap, you can use the remove() method:

myMap.remove("Orange");

Iterating over a HashMap

You can iterate over a HashMap using a for-each loop or an iterator. Here's an example of iterating using a for-each loop:

for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

Worked Example

Let's consider a simple example where we create a HashMap to store the names and ages of some people:

Map<String, Integer> people = new HashMap<>();
people.put("Alice", 25);
people.put("Bob", 30);
people.put("Charlie", 19);

// Print the names and ages of all people
for (Map.Entry<String, Integer> entry : people.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}

Output:

Alice: 25
Bob: 30
Charlie: 19

Common Mistakes

1. Forgetting to import the HashMap class

Remember to import java.util.HashMap at the beginning of your Java file:

import java.util.HashMap;

2. Using non-primitive key types

Keys in a HashMap must be instances of the Comparable interface or, more commonly, primitive types (int, long, char) wrapped in their respective wrapper classes (Integer, Long, Character).

3. Forgetting to declare the key and value types when creating a new HashMap

Always specify the key and value types when creating a new HashMap:

Map<String, Integer> myMap = new HashMap<>(); // Correct
Map myMap = new HashMap(); // Incorrect

4. Using duplicate keys

Duplicate keys are allowed in a HashMap, but they will overwrite the existing value associated with that key:

myMap.put("Apple", 10);
myMap.put("Apple", 20); // The original value (10) is lost

5. Using null keys or values

While a HashMap can store null keys and values, it's generally not recommended as it may lead to unexpected behavior:

myMap.put(null, "This is a bad practice"); // Not recommended

Practice Questions

  1. Create a HashMap to store the names and email addresses of your friends.
  2. Write a program that finds the oldest person in a group using a HashMap.
  3. Given a HashMap containing words and their frequencies, write a program that sorts the words based on their frequencies.
  4. Implement a method that merges two HashMaps into one.
  5. Write a program that checks if a given word is an anagram of another word using a HashMap.

FAQ

Q: What happens when a hash collision occurs in a HashMap?

A: When a hash collision occurs, the HashMap uses a linked list to store the colliding elements. The linked list is chained to the bucket that corresponds to the key's hash code.

Q: How does Java decide which bucket a key should be placed in a HashMap?

A: In Java, keys are hashed using their hashCode() method, and the resulting hash value is used as an index for the corresponding bucket in the underlying hash table.

Q: What is the initial capacity of a new HashMap in Java?

A: The initial capacity of a new HashMap in Java is 16. You can change this by creating a custom constructor when instantiating the HashMap object.

Q: How does the load factor affect the performance of a HashMap in Java?

A: The load factor determines when the HashMap should resize itself to accommodate more elements. A higher load factor means that the HashMap will grow slower, but it may lead to slower access times due to increased hash collisions. On the other hand, a lower load factor results in faster access times but requires more memory for the HashMap's internal data structures.

Q: How can I create an empty HashMap in Java?

A: To create an empty HashMap in Java, you can use the following syntax:

Map<String, Integer> myEmptyMap = new HashMap<>();
Java HashMap | Java | XQA Learn