Dr. Vatsal Shah
Subject Material

Java · Collections · Topic 5

Map Interface

Master key-value storage with Map, HashMap, LinkedHashMap, SortedMap, NavigableMap, TreeMap, Hashtable, and efficient traversal using Map.Entry.

Topic progress · 1 of 15 sections

Step 1 of 15

5.1 Introduction to Map

Learning objective

Define a Map, identify keys and values, and explain why Map is separate from Collection.

The Map interface stores data in the form of key-value pairs. Each key is associated with a value. A student enrollment number can be the key and the student name can be its value.

Example key-value associations
KeyValue
101Amit
102Neha
103Raj
Java representation
import java.util.HashMap;
import java.util.Map;

Map<Integer, String> students = new HashMap<>();
students.put(101, "Amit");
students.put(102, "Neha");
students.put(103, "Raj");
Check your understanding: What does Map store instead of individual elements?

Key-value pairs.

Step 2 of 15

5.2 Characteristics of Map

Learning objective

Describe uniqueness, replacement, ordering, type, and null-handling rules for maps.

Core Map characteristics

  • Data is stored as key-value pairs
  • Keys must be unique
  • Values can be duplicated
  • Each key is associated with only one value
  • Duplicate keys replace their existing values
  • Key and value types may differ
  • Entry order depends on the implementation
  • Null handling depends on the implementation
DuplicateKeyDemo.java
import java.util.HashMap;
import java.util.Map;

public class DuplicateKeyDemo {
    public static void main(String[] args) {
        Map<Integer, String> students = new HashMap<>();
        students.put(101, "Amit");
        students.put(102, "Neha");
        students.put(101, "Raj");
        System.out.println(students);
    }
}
Possible output
{101=Raj, 102=Neha}

Amit is replaced by Raj because key 101 already exists. HashMap display order is not guaranteed.

Check your understanding: What happens when put() is called with a key that already exists?

The existing value associated with that key is replaced.

Step 3 of 15

5.3 Map Hierarchy

Learning objective

Recognize the main Map interfaces and implementation classes.

Simplified Map hierarchy
Map
|-- HashMap
|     |-- LinkedHashMap
|-- SortedMap
|     |-- NavigableMap
|           |-- TreeMap
|-- Hashtable
Main Map implementations
ImplementationPrimary behavior
HashMapFast lookup; no guaranteed order
LinkedHashMapFast lookup with insertion order
TreeMapKeys maintained in sorted order
HashtableLegacy synchronized map
Check your understanding: Which class implements NavigableMap and stores keys in sorted order?

TreeMap.

Step 4 of 15

5.4 Creating a Map

Learning objective

Declare maps through the Map interface and identify their generic key and value types.

Recommended declaration
Map<Integer, String> students = new HashMap<>();

Reading the declaration

  • Map is the interface
  • HashMap is the implementation class
  • Integer is the key type
  • String is the value type
  • The diamond operator lets Java infer the generic types
Changing the implementation
Map<Integer, String> students = new TreeMap<>();

Both declarations expose the Map operations. The implementation determines ordering, performance, null support, and navigation behavior.

Check your understanding: In Map<Integer, String>, what do Integer and String represent?

Integer is the key type and String is the value type.

Step 5 of 15

5.5 Important Map Methods

Learning objective

Match common Map requirements with the correct method.

Important Map methods
MethodDescription
put(key, value)Adds or updates an entry
putIfAbsent(key, value)Adds an entry only if the key is absent
putAll(map)Copies all entries from another map
get(key)Returns the value associated with a key
getOrDefault(key, defaultValue)Returns the value or a default value
remove(key)Removes an entry using its key
remove(key, value)Removes an entry only if both match
replace(key, value)Replaces the value of an existing key
containsKey(key)Checks whether a key exists
containsValue(value)Checks whether a value exists
size()Returns the number of entries
isEmpty()Checks whether the map is empty
clear()Removes all entries
keySet()Returns all keys as a Set
values()Returns all values as a Collection
entrySet()Returns all key-value entries as a Set
Check your understanding: Which method returns all key-value pairs as a Set?

entrySet().

Step 6 of 15

5.6 Basic Map Operations

Learning objective

Trace insertion, retrieval, replacement, searching, removal, and size operations in one program.

MapOperationsDemo.java
import java.util.LinkedHashMap;
import java.util.Map;

public class MapOperationsDemo {
    public static void main(String[] args) {
        Map<Integer, String> students = new LinkedHashMap<>();

        students.put(101, "Amit");
        students.put(102, "Neha");
        students.put(103, "Raj");
        System.out.println("Map: " + students);

        System.out.println("Student 102: " + students.get(102));
        students.put(103, "Rahul");

        System.out.println("Contains key 101: " +
                           students.containsKey(101));
        System.out.println("Contains Neha: " +
                           students.containsValue("Neha"));

        students.remove(101);
        System.out.println("Updated Map: " + students);
        System.out.println("Size: " + students.size());
    }
}
Output
Map: {101=Amit, 102=Neha, 103=Raj}
Student 102: Neha
Contains key 101: true
Contains Neha: true
Updated Map: {102=Neha, 103=Rahul}
Size: 2
Check your understanding: After key 101 is removed, how many entries remain?

Two.

Step 7 of 15

5.7 HashMap

Learning objective

Explain HashMap hashing, null support, duplicate-key behavior, performance, and order limitations.

HashMap characteristics

  • Keys must be unique
  • Values can be duplicated
  • Does not maintain insertion order
  • Does not sort keys
  • Allows one null key
  • Allows multiple null values
  • Provides fast average insertion, lookup, and removal
  • Is not synchronized
  • Uses hashCode() and equals() for keys
HashMapDemo.java
import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
    public static void main(String[] args) {
        Map<Integer, String> students = new HashMap<>();
        students.put(101, "Amit");
        students.put(102, "Neha");
        students.put(103, "Raj");
        students.put(104, "Neha");
        students.put(null, "Unknown");

        System.out.println(students);
        students.put(101, "Riya");
        System.out.println("After updating key 101: " + students);
    }
}
Possible output
{null=Unknown, 101=Amit, 102=Neha, 103=Raj, 104=Neha}
After updating key 101: {null=Unknown, 101=Riya, 102=Neha, 103=Raj, 104=Neha}
HashMap average complexity
OperationAverage complexity
put()O(1)
get()O(1)
remove()O(1)
containsKey()O(1)
TraversalO(n)
Check your understanding: How many null keys can a HashMap contain?

One null key; it may contain multiple null values.

Step 8 of 15

5.8 LinkedHashMap

Learning objective

Use LinkedHashMap when fast key lookup and predictable insertion order are both required.

LinkedHashMap characteristics

  • Maintains insertion order
  • Keys must be unique
  • Values can be duplicated
  • Allows one null key
  • Allows multiple null values
  • Is slightly slower than HashMap
  • Is not synchronized
LinkedHashMapDemo.java
import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapDemo {
    public static void main(String[] args) {
        Map<Integer, String> students = new LinkedHashMap<>();
        students.put(103, "Raj");
        students.put(101, "Amit");
        students.put(102, "Neha");
        System.out.println(students);
    }
}
Output
{103=Raj, 101=Amit, 102=Neha}

Use LinkedHashMap when

  • Fast key-based access is required
  • Insertion order must be preserved
  • Sorting is not required
Check your understanding: Which requirement distinguishes LinkedHashMap from HashMap?

Preserving insertion order.

Step 9 of 15

5.9 SortedMap

Learning objective

Explain sorted-key behavior and use the key-range methods declared by SortedMap.

SortedMap is a child interface of Map. It maintains entries in ascending order of their keys. TreeMap is its standard implementation.

SortedMap declaration
SortedMap<Integer, String> students = new TreeMap<>();
Important SortedMap methods
MethodDescription
firstKey()Returns the smallest key
lastKey()Returns the largest key
headMap(key)Returns entries with keys smaller than the specified key
tailMap(key)Returns entries with keys greater than or equal to the specified key
subMap(from, to)Returns entries within a key range
comparator()Returns the comparator used for sorting
Check your understanding: Does headMap(key) include entries smaller than or greater than the specified key?

Entries with keys smaller than the specified key.

Step 10 of 15

5.10 NavigableMap

Learning objective

Use closest-match, endpoint, removal, and reverse-order navigation methods.

NavigableMap extends SortedMap and provides methods to locate the closest matching keys and entries.

Important NavigableMap methods
MethodDescription
lowerKey(key)Greatest key strictly smaller than the given key
floorKey(key)Greatest key smaller than or equal to the given key
ceilingKey(key)Smallest key greater than or equal to the given key
higherKey(key)Smallest key strictly greater than the given key
firstEntry()Returns the first key-value entry
lastEntry()Returns the last key-value entry
pollFirstEntry()Returns and removes the first entry
pollLastEntry()Returns and removes the last entry
descendingMap()Returns entries in reverse key order
Check your understanding: Which method finds the smallest key greater than or equal to a target?

ceilingKey(key).

Step 11 of 15

5.11 TreeMap

Learning objective

Apply sorted-key storage and NavigableMap operations and analyze their complexity.

TreeMap characteristics

  • Keys are automatically sorted
  • Keys must be unique
  • Values can be duplicated
  • Normally does not allow a null key
  • Allows multiple null values
  • Provides range-searching operations
  • Is not synchronized
  • Keys must be mutually comparable
TreeMapDemo.java
import java.util.TreeMap;

public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap<Integer, String> students = new TreeMap<>();
        students.put(103, "Raj");
        students.put(101, "Amit");
        students.put(105, "Riya");
        students.put(102, "Neha");

        System.out.println(students);
        System.out.println("First key: " + students.firstKey());
        System.out.println("Last key: " + students.lastKey());
        System.out.println("Lower key than 103: " + students.lowerKey(103));
        System.out.println("Higher key than 103: " + students.higherKey(103));
    }
}
Output
{101=Amit, 102=Neha, 103=Raj, 105=Riya}
First key: 101
Last key: 105
Lower key than 103: 102
Higher key than 103: 105
Reverse key ordering
TreeMap<Integer, String> students =
        new TreeMap<>(Comparator.reverseOrder());
TreeMap complexity
OperationComplexity
put()O(log n)
get()O(log n)
remove()O(log n)
containsKey()O(log n)
Check your understanding: What are lowerKey(103) and higherKey(103) for keys 101, 102, 103, and 105?

102 and 105.

Step 12 of 15

5.12 Hashtable

Learning objective

Recognize Hashtable’s legacy synchronized behavior and its null restrictions.

Hashtable characteristics

  • Keys must be unique
  • Values can be duplicated
  • Does not maintain insertion order
  • Does not sort entries
  • Does not allow null keys
  • Does not allow null values
  • Its methods are synchronized
  • It is generally slower than HashMap
  • It is mainly used in older Java programs
HashtableDemo.java
import java.util.Hashtable;

public class HashtableDemo {
    public static void main(String[] args) {
        Hashtable<Integer, String> students = new Hashtable<>();
        students.put(101, "Amit");
        students.put(102, "Neha");
        students.put(103, "Raj");

        System.out.println(students);
        System.out.println("Student 102: " + students.get(102));
    }
}
Possible output
{103=Raj, 102=Neha, 101=Amit}
Student 102: Neha
Check your understanding: Can Hashtable store a null value?

No. Hashtable does not allow null keys or null values.

Step 13 of 15

5.13 Traversing a Map

Learning objective

Traverse keys, values, and complete entries and select the most efficient view for the required data.

MapTraversalDemo.java
import java.util.LinkedHashMap;
import java.util.Map;

public class MapTraversalDemo {
    public static void main(String[] args) {
        Map<Integer, String> students = new LinkedHashMap<>();
        students.put(101, "Amit");
        students.put(102, "Neha");
        students.put(103, "Raj");

        System.out.println("Keys:");
        for (Integer key : students.keySet()) {
            System.out.println(key);
        }

        System.out.println("Values:");
        for (String value : students.values()) {
            System.out.println(value);
        }

        System.out.println("Entries:");
        for (Map.Entry<Integer, String> entry : students.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}
Output
Keys:
101
102
103
Values:
Amit
Neha
Raj
Entries:
101 : Amit
102 : Neha
103 : Raj
Choose a Map view
Required dataView
Keys onlykeySet()
Values onlyvalues()
Keys and values togetherentrySet()
Check your understanding: Which traversal view avoids a separate lookup when both key and value are required?

entrySet().

Step 14 of 15

5.14 Map.Entry

Learning objective

Read and update a single key-value association through Map.Entry.

Map.Entry methods
MethodDescription
getKey()Returns the key
getValue()Returns the value
setValue(value)Updates the value
MapEntryDemo.java
import java.util.LinkedHashMap;
import java.util.Map;

public class MapEntryDemo {
    public static void main(String[] args) {
        Map<Integer, String> students = new LinkedHashMap<>();
        students.put(101, "Amit");
        students.put(102, "Neha");
        students.put(103, "Raj");

        for (Map.Entry<Integer, String> entry : students.entrySet()) {
            if (entry.getKey() == 102) {
                entry.setValue("Priya");
            }
        }

        System.out.println(students);
    }
}
Output
{101=Amit, 102=Priya, 103=Raj}
Check your understanding: Which Map.Entry method changes the value for its current key?

setValue(value).

Step 15 of 15

5.15 Comparison of Map Implementations

Learning objective

Select the correct Map implementation from ordering, null handling, synchronization, and performance requirements.

Map implementation comparison
FeatureHashMapLinkedHashMapTreeMapHashtable
Key orderNo guaranteeInsertion orderSorted orderNo guarantee
Duplicate keysNot allowedNot allowedNot allowedNot allowed
Duplicate valuesAllowedAllowedAllowedAllowed
null keyOne allowedOne allowedNormally not allowedNot allowed
null valuesAllowedAllowedAllowedNot allowed
SynchronizedNoNoNoYes
PerformanceFast average lookupSlightly slower than HashMapO(log n) key operationsSlower due to synchronization
TypeModernModernModernLegacy
Quick selection guide
RequirementRecommended implementation
Fast general-purpose key lookupHashMap
Insertion order must be preservedLinkedHashMap
Sorted keys or range navigationTreeMap
Maintaining older synchronized codeHashtable; prefer modern concurrent alternatives for new code
Check your understanding: Which implementation should be selected when keys must remain sorted?

TreeMap.