W3schools Java HashMap Tutorial Guide Learn With Examples

Robert Jul 13, 2026

Java's HashMap, first introduced in Java 1.2, is a powerful part of the Java Collection Framework. It's a popular data structure due to its fast retrieval times and ability to store data in key-value pairs. This article explores the HashMap class in detail, with examples and best practices.

HashMap vs HashSet in Java ⚑ Key Differences Explained (DSA Cheat Sheet)
HashMap vs HashSet in Java ⚑ Key Differences Explained (DSA Cheat Sheet)

HashMap implements the Map interface and is a widely-used class for storing and mapping objects. It uses a hashed data structure to store keys and values. Before diving into its operational details, let's look at its basic usage and why it's so effective.

Java HashMap Explained πŸ—ΊοΈ | DSA Pattern Cheat Sheet for Coding Interviews
Java HashMap Explained πŸ—ΊοΈ | DSA Pattern Cheat Sheet for Coding Interviews

Getting Started with Java HashMap

A HashMap in Java is an unordered collection where instances of key objects map to their corresponding values. It doesn't maintain any insertion order and doesn't provide a way to iterate through keys, values, or entries in any particular order.

Hashset vs Hashmap
Hashset vs Hashmap

HashMap uses the put method to add elements and the get method to retrieve them:

Example:

Explore hashset vs hashmap in java
Explore hashset vs hashmap in java

HashMap<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
int value = map.get("one"); // Retrieves the value associated with key "one"

HashMap Initialization and Iteration

HashMaps can be initialized in several ways. They can be empty, with an initial capacity, or even with an initial set of key-value pairs:

HashMap<String, Integer> map1 = new HashMap<>();
HashMap<String, Integer> map2 = new HashMap<>(20); // Initial capacity of 20
HashMap<String, Integer> map3 = new HashMap<>(map1); // Copies values from map1
HashMap<String, Integer> map4 = new HashMap<>(Map.of("one", 1, "two", 2)); // Initialized with key-value pairs

To iterate through a HashMap, you can use the entrySet() method, which returns a set view of the mappings in this map:

Learn Java Collections Fast πŸš€ | ArrayList HashMap Set Queue Explained
Learn Java Collections Fast πŸš€ | ArrayList HashMap Set Queue Explained

Example:

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    int value = entry.getValue();
    // Process the key and value
}

HashMap Methods and Special Features

HashMap offers a myriad of methods for various operations. Here are some of the most useful ones:

Hashset initialization java - HashSet Class in Java with Example | Learn What is HashSet in Java & How to get started with it - BTech Geeks
Hashset initialization java - HashSet Class in Java with Example | Learn What is HashSet in Java & How to get started with it - BTech Geeks
  • size(): Returns the number of key-value pairs in this map.
  • isEmpty(): Returns true if this map contains no key-value pairs.
  • remove(Object key): Removes the mapping for a key from this map if it is present.
  • clear(): Removes all of the mappings from this map.

Performance and Best Practices

10 Example of Hashtable in Java – Java Hashtable Tutorial
10 Example of Hashtable in Java – Java Hashtable Tutorial
an image of a computer screen with many lines and numbers on the screen, all in different colors
an image of a computer screen with many lines and numbers on the screen, all in different colors
Difference Between HashMap and Hashtable
Difference Between HashMap and Hashtable
30 Days of Java – Day 23 | Java HashMap Explained for Beginners
30 Days of Java – Day 23 | Java HashMap Explained for Beginners
Array vs HashMap ⚑ Key Differences Explained Simply
Array vs HashMap ⚑ Key Differences Explained Simply
Difference Between Map and HashMap in Java | Baeldung
Difference Between Map and HashMap in Java | Baeldung
Bridge Built! Superior Python, Java, JS Expertise: Cross Over – Order for Connected Creations!
Bridge Built! Superior Python, Java, JS Expertise: Cross Over – Order for Connected Creations!
Java Basics Cheat Sheet | Core Java Programming Notes for Beginners | AKTU Notes
Java Basics Cheat Sheet | Core Java Programming Notes for Beginners | AKTU Notes
a block diagram with the words hash sum and hash function in each block, it is labeled
a block diagram with the words hash sum and hash function in each block, it is labeled
Difference between HashMap vs IdentityHashMap in Java? Example
Difference between HashMap vs IdentityHashMap in Java? Example
java at a glance 😎
java at a glance 😎
Java Cheatsheet
Java Cheatsheet
Java Patterns Notes 1
Java Patterns Notes 1
Veil Lifted! Prime Python, Java, JavaScript Expertise: Mystery Solved – Order for Clear Victories!
Veil Lifted! Prime Python, Java, JavaScript Expertise: Mystery Solved – Order for Clear Victories!
Learn Java in 45 Days
Learn Java in 45 Days
java programs
java programs
How to Learn Java In 50 Days πŸ”₯πŸš€
How to Learn Java In 50 Days πŸ”₯πŸš€
Learn Java in 30 Days Only
Learn Java in 30 Days Only
Java Scanner Class Made Easy: Your Ultimate Input Cheat Sheet πŸŽ―πŸ’»
Java Scanner Class Made Easy: Your Ultimate Input Cheat Sheet πŸŽ―πŸ’»
What are Arrays in Java?
What are Arrays in Java?

HashMap is designed to provide fast retrieval, insertion, and deletion operations. In fact, all its main methods (put, get, remove) have a time complexity of O(1) on average. However, this doesn't mean you can ignore its limitations and best practices:

Optimizing Initial Capacity

To optimize performance, it's crucial to choose an appropriate initial capacity. A larger initial capacity reduces the frequency of resizing, which can lead to faster operations:

Example:

HashMap<String, Integer> map = new HashMap<>((int) (2 * Runtime.getRuntime().freeMemory() / 10)); // Gives a good initial size for a large HashMap.

HashMap vs Other Map Interfaces

While HashMap is quite versatile, it might not always be the best choice. For more complex use-cases, consider other map implementations, such as TreeMap (sorted by key) or TheadSafeMap (thread-safe).

Lastly, always remember that proper debugging and testing can prevent bugs and performance issues. Keep monitoring your HashMap's performance, especially in high-throughput scenarios.