{"id":116217,"date":"2026-06-16T19:55:51","date_gmt":"2026-06-16T14:25:51","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=116217"},"modified":"2026-06-16T19:55:53","modified_gmt":"2026-06-16T14:25:53","slug":"what-is-hashmap-in-java","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/what-is-hashmap-in-java\/","title":{"rendered":"What is HashMap in Java: How It Works, Methods, and Examples"},"content":{"rendered":"\n<p>Many Java beginners struggle to choose the right data structure when they need fast data lookup without caring about the order of elements. HashMap in Java is built exactly for this purpose, letting you store and retrieve data using a unique key in constant time. Understanding how HashMap works internally and when to use it will make you a more confident and efficient Java developer.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Quick TL;DR<\/strong><\/h2>\n\n\n\n<ul>\n<li>HashMap in Java is a data structure that stores data in key-value pairs and allows you to retrieve any value instantly using its key.&nbsp;<\/li>\n\n\n\n<li>It is part of the Java Collections Framework and implements the Map interface.<\/li>\n\n\n\n<li>HashMap allows one null key and multiple null values, does not maintain insertion order, and offers constant-time performance for get and put operations in most cases.<\/li>\n\n\n\n<li>It is one of the most widely used data structures in Java for fast data lookup and storage.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What Is HashMap in Java?<\/strong><\/h2>\n\n\n\n<p><a href=\"https:\/\/www.guvi.in\/hub\/java-tutorial\/hashmap-class\/\" target=\"_blank\" rel=\"noreferrer noopener\">HashMap in Java<\/a> is a class in the java.util package that stores data as key-value pairs. Every key in a HashMap is unique, and each key maps to exactly one value. You use the key to store a value and the same key to retrieve it later.<\/p>\n\n\n\n<p>Key characteristics of HashMap:<\/p>\n\n\n\n<ul>\n<li>Stores data as key-value pairs<\/li>\n\n\n\n<li>Keys must be unique, values can be duplicated<\/li>\n\n\n\n<li>Allows one null key and multiple null values<\/li>\n\n\n\n<li>Does not guarantee insertion order<\/li>\n\n\n\n<li>Not thread-safe by default<\/li>\n\n\n\n<li>Provides O(1) average time complexity for get and put operations<\/li>\n<\/ul>\n\n\n\n<p><strong>Read More: <\/strong><a href=\"https:\/\/www.guvi.in\/blog\/java-data-structures-unlocked\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Java Data Structures Unlocked: A Layman\u2019s Guide with Easy Examples<\/strong><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How Does HashMap Work Internally?<\/strong><\/h2>\n\n\n\n<p>Understanding the internal working of HashMap is one of the most common Java interview topics. Here is how it works under the hood.<\/p>\n\n\n\n<ol>\n<li><strong>Hashing<\/strong><\/li>\n<\/ol>\n\n\n\n<p>When you insert a key-value pair, <a href=\"https:\/\/www.guvi.in\/blog\/getting-started-with-java\/\" target=\"_blank\" rel=\"noreferrer noopener\">Java<\/a> calls the hashCode() method on the key. This produces an integer called a hash code, which is used to calculate the index of a bucket in an internal array.<\/p>\n\n\n\n<ol start=\"2\">\n<li><strong>Buckets<\/strong><\/li>\n<\/ol>\n\n\n\n<p>HashMap uses an array of linked lists called buckets. Each bucket holds one or more entries. When two keys produce the same bucket index, it is called a collision.<\/p>\n\n\n\n<ol start=\"3\">\n<li><strong>Collision Handling<\/strong><\/li>\n<\/ol>\n\n\n\n<p>Java handles collisions using chaining. Multiple entries with the same bucket index are stored as a linked list at that index. From Java 8 onwards, when the number of entries in a single bucket exceeds 8, the linked list is converted to a balanced binary tree <a href=\"https:\/\/www.guvi.in\/blog\/red-black-trees-working-properties-applications\/\" target=\"_blank\" rel=\"noreferrer noopener\">(Red-Black Tree) <\/a>for faster lookup.<\/p>\n\n\n\n<ol start=\"4\">\n<li><strong>Retrieval<\/strong><\/li>\n<\/ol>\n\n\n\n<p>When you call get(key), Java computes the hash code of the key, finds the correct bucket, and then uses equals() to find the exact entry within that bucket.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Create and Use a HashMap in Java<\/strong><\/h2>\n\n\n\n<p>Creating a HashMap is straightforward. Here is the basic syntax:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>import java.util.HashMap;<br><br>HashMap&lt;String, Integer&gt; studentMarks = new HashMap&lt;&gt;();<br><br>\/\/ Adding key-value pairs<br>studentMarks.put(&#8220;Arun&#8221;, 85);<br>studentMarks.put(&#8220;Priya&#8221;, 92);<br>studentMarks.put(&#8220;Rahul&#8221;, 78);<br><br>\/\/ Retrieving a value<br>System.out.println(studentMarks.get(&#8220;Priya&#8221;)); \/\/ Output: 92<br><br>\/\/ Checking if a key exists<br>System.out.println(studentMarks.containsKey(&#8220;Rahul&#8221;)); \/\/ Output: true<br><br>\/\/ Removing a key<br>studentMarks.remove(&#8220;Arun&#8221;);<br><br>\/\/ Iterating over the HashMap<br>for (String name : studentMarks.keySet()) {<br>&nbsp; &nbsp; System.out.println(name + &#8220;: &#8221; + studentMarks.get(name));<br>}<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The type parameters inside the angle brackets define the data type of the key and value. In this example, the key is a <a href=\"https:\/\/www.guvi.in\/hub\/java-tutorial\/string-class-functions\/\" target=\"_blank\" rel=\"noreferrer noopener\">String<\/a> and the value is an Integer.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Important HashMap Methods in Java<\/strong><\/h2>\n\n\n\n<p>Here are the most commonly used HashMap methods you should know:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Method<\/strong><\/td><td><strong>Description<\/strong><\/td><\/tr><tr><td>put(key, value)<\/td><td>Inserts a key-value pair into the map<\/td><\/tr><tr><td>get(key)<\/td><td>Returns the value associated with the key<\/td><\/tr><tr><td>remove(key)<\/td><td>Removes the entry for the specified key<\/td><\/tr><tr><td>containsKey(key)<\/td><td>Returns true if the key exists in the map<\/td><\/tr><tr><td>containsValue(value)<\/td><td>Returns true if the value exists in the map<\/td><\/tr><tr><td>keySet()<\/td><td>Returns a Set of all keys<\/td><\/tr><tr><td>values()<\/td><td>Returns a Collection of all values<\/td><\/tr><tr><td>entrySet()<\/td><td>Returns a Set of all key-value pairs<\/td><\/tr><tr><td>size()<\/td><td>Returns the number of key-value pairs<\/td><\/tr><tr><td>isEmpty()<\/td><td>Returns true if the map has no entries<\/td><\/tr><tr><td>clear()<\/td><td>Removes all entries from the map<\/td><\/tr><tr><td>getOrDefault(key, default)<\/td><td>Returns the value or a default if key is absent<\/td><\/tr><tr><td>putIfAbsent(key, value)<\/td><td>Inserts only if the key is not already present<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>HashMap vs HashTable in Java<\/strong><\/h2>\n\n\n\n<p>HashMap and HashTable are often confused by beginners. Here is a clear comparison:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Feature<\/strong><\/td><td><strong>HashMap<\/strong><\/td><td><strong>HashTable<\/strong><\/td><\/tr><tr><td>Thread safety<\/td><td>Not thread-safe<\/td><td>Thread-safe (synchronized)<\/td><\/tr><tr><td>Null keys<\/td><td>Allows one null key<\/td><td>Does not allow null keys<\/td><\/tr><tr><td>Null values<\/td><td>Allows multiple null values<\/td><td>Does not allow null values<\/td><\/tr><tr><td>Performance<\/td><td>Faster<\/td><td>Slower due to synchronisation<\/td><\/tr><tr><td>Introduced in<\/td><td>Java 1.2 (Collections Framework)<\/td><td>Java 1.0 (legacy class)<\/td><\/tr><tr><td>Recommended<\/td><td>Yes, for most use cases<\/td><td>No, use ConcurrentHashMap instead<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>In modern Java development, HashMap is preferred for single-threaded applications. For multi-threaded environments, use ConcurrentHashMap instead of HashTable.<\/p>\n\n\n\n<div style=\"background-color: #099f4e; border: 3px solid #110053; border-radius: 12px; padding: 18px 22px; color: #FFFFFF; font-family: Montserrat, Helvetica, sans-serif; line-height: 1.6; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); max-width: 800px;\">\n  <strong style=\"font-size: 22px; color: #FFFFFF;\">\ud83d\udca1 Did You Know?<\/strong>\n  <p style=\"margin-top: 14px;\">\n    From <strong>Java 8<\/strong> onwards, <strong>HashMap<\/strong> includes a key optimization for handling hash collisions. When the number of entries in a single bucket exceeds a threshold (typically 8), the underlying structure is transformed from a <strong>linked list<\/strong> into a <strong>Red-Black Tree<\/strong>. This change significantly improves performance in worst-case scenarios, reducing lookup time from <strong>O(n)<\/strong> to <strong>O(log n)<\/strong>. This hybrid design ensures that HashMap remains efficient both in average cases (with good hashing) and in edge cases where many keys collide into the same bucket, making it one of the most robust and widely used data structures in Java.\n  <\/p>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Real-World Example of HashMap in Java<\/strong><\/h2>\n\n\n\n<p>Consider an online food delivery application that needs to track how many times each menu item has been ordered during the day.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td>import java.util.HashMap;<br><br>HashMap&lt;String, Integer&gt; orderCount = <strong>new<\/strong> HashMap&lt;&gt;();<br><br>String[] orders = {&#8220;Biryani&#8221;, &#8220;Dosa&#8221;, &#8220;Biryani&#8221;, &#8220;Idli&#8221;, &#8220;Dosa&#8221;, &#8220;Biryani&#8221;};<br><br><strong>for<\/strong> (String item : orders) {<br>&nbsp; &nbsp; orderCount.put(item, orderCount.getOrDefault(item, 0) + 1);<br>}<br><br>System.out.println(orderCount);<br>\/\/ Output: {Biryani=3, Dosa=2, Idli=1}<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Here, the getOrDefault method retrieves the current order count for an item and adds 1. If the item is not yet in the map, it starts from 0. This pattern is widely used in e-commerce and analytics systems to count occurrences of events or items efficiently.<\/p>\n\n\n\n<div style=\"background-color: #099f4e; border: 3px solid #110053; border-radius: 12px; padding: 18px 22px; color: #FFFFFF; font-family: Montserrat, Helvetica, sans-serif; line-height: 1.6; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); max-width: 800px;\">\n  <strong style=\"font-size: 22px; color: #FFFFFF;\">\ud83d\udca1 Did You Know?<\/strong>\n  <p style=\"margin-top: 14px;\">\n    <strong>HashMap<\/strong> is one of the most frequently tested topics in <strong>Java technical interviews<\/strong> across both Indian and global tech companies. Developer surveys and interview trend analyses consistently show that core concepts such as hashing, collision handling, and the internal working of <code>hashCode()<\/code> and <code>equals()<\/code> appear in a large share of Java interview question sets for both fresher and experienced roles. Because HashMap forms the backbone of many real-world systems, interviewers often use it to evaluate a candidate\u2019s understanding of data structures, performance trade-offs, and runtime behavior in practical scenarios.\n  <\/p>\n<\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Common Mistakes When Using HashMap in Java<\/strong><\/h2>\n\n\n\n<p><strong>1. Not overriding hashCode() and equals() for custom key objects:<\/strong> When you use a custom class as a HashMap key, you must override both hashCode() and equals(). Without this, two logically identical objects will be treated as different keys, leading to duplicate entries and incorrect lookups.<\/p>\n\n\n\n<p><strong>2. Modifying a HashMap while iterating over it:<\/strong> Changing a HashMap during iteration using a regular for-each loop throws a ConcurrentModificationException. Use an Iterator or collect the keys to modify separately if you need to remove entries during iteration.<\/p>\n\n\n\n<p><strong>3. Using HashMap in multi-threaded code without synchronisation:<\/strong> HashMap is not thread-safe. Using it across multiple threads without synchronisation causes data corruption and unpredictable behaviour. Use ConcurrentHashMap for thread-safe operations instead.<\/p>\n\n\n\n<p><strong>4. Assuming HashMap maintains insertion order:<\/strong> HashMap does not guarantee any order. If you need entries in insertion order, use LinkedHashMap. If you need sorted order by key, use TreeMap.<\/p>\n\n\n\n<p><strong>5. Ignoring the initial capacity and load factor:<\/strong> HashMap resizes itself when the number of entries exceeds the load factor threshold, which is 0.75 by default. Frequent resizing is expensive. If you know the approximate size of data upfront, initialise the HashMap with a suitable capacity to avoid unnecessary resizing.<\/p>\n\n\n\n<p>Want to master Java collections, data structures, and object-oriented programming with real projects? Explore <strong>HCL GUVI&#8217;s <\/strong><a href=\"https:\/\/www.guvi.in\/courses\/programming\/java-programming\/v?utm_source=blog&amp;utm_medium=hyperlink&amp;utm_campaign=hashmap-in-java\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Java Programming Course<\/strong><\/a>, designed for beginners with hands-on practice and guided learning.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>As Java continues to power enterprise applications, Android development, and backend systems worldwide, HashMap remains one of the most used and most interviewed data structures in the language.&nbsp;<\/p>\n\n\n\n<p>Mastering how HashMap stores data internally, knowing its key methods, and understanding when to use it over alternatives like LinkedHashMap, TreeMap, or ConcurrentHashMap will significantly strengthen your Java skills. Start by practising common HashMap operations, then try implementing frequency counters or caching logic using HashMap in small projects.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>FAQ<\/strong><\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1781237833851\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>1. What is HashMap in Java?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>HashMap in Java is a class that stores data as key-value pairs, where each key is unique and maps to exactly one value. It is part of the Java Collections Framework and provides constant-time performance for basic operations like get and put.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1781237839590\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>2. How does HashMap work internally in Java?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>HashMap uses an array of buckets internally. When you insert a key-value pair, Java computes the hash code of the key to find the bucket index. If multiple keys map to the same bucket, they are stored as a linked list or a Red-Black Tree from Java 8 onwards.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1781237849876\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>3. What is the difference between HashMap and HashTable in Java?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>HashMap is not thread-safe and allows null keys and values. HashTable is thread-safe but slower and does not allow null keys or values. For modern multi-threaded applications, ConcurrentHashMap is recommended over HashTable.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1781237860554\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>4. Can HashMap have duplicate keys in Java?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>No. HashMap does not allow duplicate keys. If you insert a value with an existing key, the new value replaces the old one. However, duplicate values are allowed across different keys.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1781237869026\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>5. What is the default initial capacity and load factor of HashMap in Java?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>The default initial capacity of a HashMap is 16 buckets, and the default load factor is 0.75. When the number of entries exceeds 75% of the current capacity, HashMap automatically resizes by doubling its capacity.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1781237887483\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>6. What is the difference between HashMap and LinkedHashMap in Java?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>HashMap does not maintain any order of entries. LinkedHashMap maintains insertion order, meaning entries are returned in the order they were added. Use LinkedHashMap when order matters and HashMap when it does not.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1781237898518\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>7. What happens if two keys have the same hash code in HashMap?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>This is called a hash collision. HashMap handles it using chaining, where multiple entries with the same bucket index are stored in a linked list. From Java 8 onwards, if the list grows beyond 8 entries, it is converted to a Red-Black Tree for faster lookup.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1781237907454\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \"><strong>8. Is HashMap thread-safe in Java?<\/strong><\/h3>\n<div class=\"rank-math-answer \">\n\n<p>No, HashMap is not thread-safe. Concurrent read and write operations from multiple threads can cause data corruption. Use ConcurrentHashMap from the java.util.concurrent package for thread-safe key-value storage in multi-threaded applications.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>Many Java beginners struggle to choose the right data structure when they need fast data lookup without caring about the order of elements. HashMap in Java is built exactly for this purpose, letting you store and retrieve data using a unique key in constant time. Understanding how HashMap works internally and when to use it [&hellip;]<\/p>\n","protected":false},"author":63,"featured_media":116938,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[720],"tags":[],"views":"32","authorinfo":{"name":"Vishalini Devarajan","url":"https:\/\/www.guvi.in\/blog\/author\/vishalini\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2026\/06\/what-is-hashmap-in-java-300x115.webp","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/116217"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/63"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=116217"}],"version-history":[{"count":2,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/116217\/revisions"}],"predecessor-version":[{"id":116939,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/116217\/revisions\/116939"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/116938"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=116217"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=116217"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=116217"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}