Course contentsShow
← Java
Lesson 997 of 2,87023. Collections Framework OverviewFree lesson

HashMap: Key-Value Pairs with Hashing

Explore HashMap's constant-time key lookups, insertions, and deletions for associating keys with values.

HashMap: Key-Value Pairs with Hashing

What You'll Learn

You'll discover how HashMap provides lightning-fast lookups by associating keys with values using a hashing mechanism.

The Core Idea

A HashMap<K,V> stores key-value pairs where each key maps to exactly one value. Unlike lists that use numeric indices (0, 1, 2...), HashMap lets you use any object as the "index" (the key) to retrieve its associated value.

The magic happens through hashing: when you insert or look up a key, HashMap runs it through a hash function that converts it to a number, determining where to store (or find) the value in memory. This gives you constant-time performance — typically O(1) — for insertions, retrievals, and deletions, regardless of how many entries you have.

The Dictionary Analogy

Think of a physical dictionary. Instead of reading every page sequentially to find "zebra," you jump directly to the 'Z' section because you know the alphabetical ordering. HashMap is similar but even faster: the hash function calculates the exact "bucket" location instantly, like having a magic page number for every word.

Key Characteristics

  • Fast lookups: Find values by key in constant time
  • Fast insertions: Add new key-value pairs in constant time
  • Fast deletions: Remove pairs by key in constant time
  • No guaranteed order: Entries aren't stored in insertion or sorted order
  • Unique keys: Each key appears only once; duplicate keys replace the old value
  • Null permitted: Both null keys and null values are allowed

When to Use HashMap

Choose HashMap when you need to quickly find, add, or remove data based on a unique identifier — like looking up user profiles by username, storing configuration settings by name, or caching computed results by input parameters.

Key Takeaway: HashMap uses hashing to deliver constant-time key-based operations, making it ideal for fast lookups, insertions, and deletions when you don't need ordering.