1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Hashmap Basics
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
12Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Hashmap Basics

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
12Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

HashMap

Overview

A HashMap is a foundational Key-Value data structure that stores pairs of data. Instead of locating data by a numeric index (like an array), you retrieve data using a meaningful key. This makes data lookup both semantically rich and blazing fast.

Internally, HashMap is powered by an array of 'buckets' and a Hash Function. When you call map.put("name", "Alice"), the JVM runs the hashCode() method on the key ("name"), converts it into an array index, and stores the value at that location. When you later call map.get("name"), the exact same hash is computed, the same bucket is found, and the value is retrieved in amortized O(1) time.

A Hash Collision occurs when two different keys produce the same hash code (same bucket index). Java resolves this using Chaining — each bucket holds a linked list (or a Red-Black tree for 8+ collisions in Java 8+) of all key-value pairs that collided there. HashMaps are fundamentally unordered — they make no guarantee about the order of iteration.

Syntax

Core HashMap Operations
java
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        
        // 1. Putting Key-Value Pairs
        scores.put("Alice", 95);
        scores.put("Bob", 88);
        scores.put("Charlie", 72);
        
        // 2. Retrieving Values
        System.out.println(scores.get("Alice")); // 95
        System.out.println(scores.get("NoKey")); // null (key doesn't exist)
        
        // 3. Safe Retrieval with Default
        int aliceScore = scores.getOrDefault("NoKey", 0); // Returns 0, not null
        
        // 4. Checking Existence
        System.out.println(scores.containsKey("Bob")); // true
        
        // 5. Iterating (Order NOT guaranteed!)
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + " scored: " + entry.getValue());
        }
        
        // 6. Powerful Java 8+ method
        // If key exists: adds 10. If key absent: inserts 10.
        scores.merge("Alice", 10, Integer::sum); // Alice → 105
    }
}

Common Pitfalls

  • Depending on iteration order. HashMap makes absolutely NO guarantee about the order you will get your key-value pairs when you iterate. If order matters, use LinkedHashMap (insertion-order) or TreeMap (natural sort order of keys).
  • Using mutable objects as Keys. The HashMap uses the key's hashCode() to find the bucket. If you use an object as a key and then mutate it after inserting, its hashCode() changes, and the map can no longer find it — it's lost permanently! Always use immutable objects (like String, Integer) as HashMap keys.
  • Calling get() without null-checking. If the key doesn't exist, get() returns null. If you immediately try to unbox the result (e.g., int score = scores.get("Unknown");), you get a NullPointerException. Always use getOrDefault() or check containsKey() first.

Interview Questions

What is the time complexity of put() and get() in a HashMap?

Both are amortized O(1). In the absolute worst-case scenario (every single key produces the same hash code, causing massive collisions), it degrades to O(N). In practice, with a well-distributed hash function and the default load factor, it is effectively constant time.

What is the default initial capacity and load factor of a HashMap, and what does the load factor mean?

Default initial capacity is 16 buckets, and the default load factor is 0.75. When the number of entries exceeds 75% of the current capacity (12 entries for a capacity-16 map), the HashMap automatically doubles its internal array size and rehashes all existing entries — an expensive O(N) operation.

What is the difference between HashMap, LinkedHashMap, and TreeMap?

HashMap is unordered — O(1) get/put but no iteration order guarantee. LinkedHashMap maintains insertion order by linking buckets — O(1) operations but slightly more memory. TreeMap stores keys in sorted (natural or custom Comparator) order — O(log N) for all operations because it is backed by a Red-Black tree.

Real-World Example

Rate limiting middleware in an API server uses a HashMap to track how many requests each user has made in the last minute. The user's ID is the key, and the request count is the value, enabling O(1) lookup on every incoming request.

example
java
Map<String, Integer> requestCounts = new HashMap<>();

public boolean isRateLimited(String userId) {
    int count = requestCounts.getOrDefault(userId, 0);
    if (count >= 100) { // More than 100 requests per minute
        return true; // Block the request
    }
    requestCounts.put(userId, count + 1);
    return false;
}

Check Your Knowledge

Test your understanding of HashMap with these quick questions.

Question 1

What does `HashMap.get()` return if the key does not exist?

Question 2

Which collection should you use if you need HashMap behavior but with entries always iterated in insertion order?

Question 3

What happens internally when you call `put()` and the HashMap's load factor is exceeded?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

HashMap

Overview

A HashMap is a foundational Key-Value data structure that stores pairs of data. Instead of locating data by a numeric index (like an array), you retrieve data using a meaningful key. This makes data lookup both semantically rich and blazing fast.

Internally, HashMap is powered by an array of 'buckets' and a Hash Function. When you call map.put("name", "Alice"), the JVM runs the hashCode() method on the key ("name"), converts it into an array index, and stores the value at that location. When you later call map.get("name"), the exact same hash is computed, the same bucket is found, and the value is retrieved in amortized O(1) time.

A Hash Collision occurs when two different keys produce the same hash code (same bucket index). Java resolves this using Chaining — each bucket holds a linked list (or a Red-Black tree for 8+ collisions in Java 8+) of all key-value pairs that collided there. HashMaps are fundamentally unordered — they make no guarantee about the order of iteration.

Syntax

Core HashMap Operations
java
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> scores = new HashMap<>();
        
        // 1. Putting Key-Value Pairs
        scores.put("Alice", 95);
        scores.put("Bob", 88);
        scores.put("Charlie", 72);
        
        // 2. Retrieving Values
        System.out.println(scores.get("Alice")); // 95
        System.out.println(scores.get("NoKey")); // null (key doesn't exist)
        
        // 3. Safe Retrieval with Default
        int aliceScore = scores.getOrDefault("NoKey", 0); // Returns 0, not null
        
        // 4. Checking Existence
        System.out.println(scores.containsKey("Bob")); // true
        
        // 5. Iterating (Order NOT guaranteed!)
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + " scored: " + entry.getValue());
        }
        
        // 6. Powerful Java 8+ method
        // If key exists: adds 10. If key absent: inserts 10.
        scores.merge("Alice", 10, Integer::sum); // Alice → 105
    }
}

Common Pitfalls

  • Depending on iteration order. HashMap makes absolutely NO guarantee about the order you will get your key-value pairs when you iterate. If order matters, use LinkedHashMap (insertion-order) or TreeMap (natural sort order of keys).
  • Using mutable objects as Keys. The HashMap uses the key's hashCode() to find the bucket. If you use an object as a key and then mutate it after inserting, its hashCode() changes, and the map can no longer find it — it's lost permanently! Always use immutable objects (like String, Integer) as HashMap keys.
  • Calling get() without null-checking. If the key doesn't exist, get() returns null. If you immediately try to unbox the result (e.g., int score = scores.get("Unknown");), you get a NullPointerException. Always use getOrDefault() or check containsKey() first.

Interview Questions

What is the time complexity of put() and get() in a HashMap?

Both are amortized O(1). In the absolute worst-case scenario (every single key produces the same hash code, causing massive collisions), it degrades to O(N). In practice, with a well-distributed hash function and the default load factor, it is effectively constant time.

What is the default initial capacity and load factor of a HashMap, and what does the load factor mean?

Default initial capacity is 16 buckets, and the default load factor is 0.75. When the number of entries exceeds 75% of the current capacity (12 entries for a capacity-16 map), the HashMap automatically doubles its internal array size and rehashes all existing entries — an expensive O(N) operation.

What is the difference between HashMap, LinkedHashMap, and TreeMap?

HashMap is unordered — O(1) get/put but no iteration order guarantee. LinkedHashMap maintains insertion order by linking buckets — O(1) operations but slightly more memory. TreeMap stores keys in sorted (natural or custom Comparator) order — O(log N) for all operations because it is backed by a Red-Black tree.

Real-World Example

Rate limiting middleware in an API server uses a HashMap to track how many requests each user has made in the last minute. The user's ID is the key, and the request count is the value, enabling O(1) lookup on every incoming request.

example
java
Map<String, Integer> requestCounts = new HashMap<>();

public boolean isRateLimited(String userId) {
    int count = requestCounts.getOrDefault(userId, 0);
    if (count >= 100) { // More than 100 requests per minute
        return true; // Block the request
    }
    requestCounts.put(userId, count + 1);
    return false;
}

Check Your Knowledge

Test your understanding of HashMap with these quick questions.

Question 1

What does `HashMap.get()` return if the key does not exist?

Question 2

Which collection should you use if you need HashMap behavior but with entries always iterated in insertion order?

Question 3

What happens internally when you call `put()` and the HashMap's load factor is exceeded?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A