HOME HTML EDITOR C JAVA PHP

The Java Map Interface: Key-Value Associations

A Map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. While technically not a subtype of the Collection interface, it is a core pillar of the Java Collections Framework.

1. The Core Concept: Key and Value

In a Map, data is stored in entries. An Entry is a simple object containing a Key and its associated Value. The Key acts as a unique identifier used to retrieve the Value later.

The Keys

Must be unique. If you put a new value with an existing key, the old value is overwritten. Usually, keys are immutable (like String or Integer).

The Values

Can be duplicated. Multiple different keys can point to the same value (e.g., two people can have the same birth year).

2. Hierarchy of Map Implementations

Just like Sets, Maps come in different flavors depending on your requirements for speed, ordering, and sorting.

Implementation Ordering Null Support Performance
HashMap None (Unpredictable) 1 Null Key, Many Null Values $O(1)$
LinkedHashMap Insertion Order 1 Null Key, Many Null Values $O(1)$
TreeMap Sorted (by Key) No Null Keys $O(\log n)$
Hashtable None (Legacy) No Nulls (Thread-safe) $O(1)$ but slow

3. Essential Map Operations

Interacting with a Map requires a different set of methods than a List or Set:

4. How Maps Work: The Hashing Mechanism

When you call map.put("Java", 100), Java doesn't just store the string. It calculates a Hash Code for the key "Java," determines a bucket index, and stores the Entry object there. This is why lookups are nearly instantaneous regardless of whether the map has 10 or 10 million items.

5. Mastery Code Example: Employee Directory

This example demonstrates how to store custom objects in a map and iterate through them efficiently using the entrySet.

import java.util.*;

public class MapMastery {
  public static void main(String[] args) {
    Map<Integer, String> employees = new HashMap<>();

    // Storing data
    employees.put(101, "Alice");
    employees.put(102, "Bob");
    employees.put(103, "Charlie");

    // Modern Retrieval
    String name = employees.getOrDefault(104, "Not Found");

    // Efficient Iteration
    for (Map.Entry<Integer, String> entry : employees.entrySet()) {
      System.out.println("ID: " + entry.getKey() + " | Name: " + entry.getValue());
    }
  }
}

6. Java 8+ Map Enhancements

Java 8 revolutionized how we work with Maps by introducing functional methods that reduce boilerplate code:

7. The Mutability Warning

Never change a key while it is in a Map. If you use a custom User object as a key and then change the user's ID, the hashCode() will change. The Map will look for the user in the "new" bucket, fail to find it, and you will have an orphaned entry in the "old" bucket that can never be retrieved or deleted. This is why String is the most common key—it is immutable.

8. Interview Preparation: The Map Deep-Dive

Q: Why doesn't Map extend Collection?
A: A Collection is a group of individual items. A Map is a group of pairs. The methods are fundamentally different (e.g., add(E e) vs put(K k, V v)). Mixing them would violate the Interface Segregation Principle.

Q: What is a Collision?
A: A collision happens when two different keys produce the same hash code. Java stores these keys in a linked list (or tree) within the same bucket.

Q: HashMap vs Hashtable?
A: HashMap is unsynchronized, faster, and allows nulls. Hashtable is legacy, synchronized, and forbids nulls. For modern thread-safety, use ConcurrentHashMap.

Final Verdict

The Map Interface is the ultimate data retrieval system. By mastering the differences between HashMap, TreeMap, and LinkedHashMap, you can choose the right balance between speed and order. Maps turn complex $O(n)$ search problems into instant $O(1)$ lookups, making them essential for any high-performance Java application.

Next: Deep Dive into HashMap →