Java · Collections · Topic 5
Map Interface
Master key-value storage with Map, HashMap, LinkedHashMap, SortedMap, NavigableMap, TreeMap, Hashtable, and efficient traversal using Map.Entry.
Step 1 of 15
5.1 Introduction to Map
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.
| Key | Value |
|---|---|
| 101 | Amit |
| 102 | Neha |
| 103 | Raj |
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
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
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);
}
}{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
Recognize the main Map interfaces and implementation classes.
Map
|-- HashMap
| |-- LinkedHashMap
|-- SortedMap
| |-- NavigableMap
| |-- TreeMap
|-- Hashtable| Implementation | Primary behavior |
|---|---|
| HashMap | Fast lookup; no guaranteed order |
| LinkedHashMap | Fast lookup with insertion order |
| TreeMap | Keys maintained in sorted order |
| Hashtable | Legacy 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
Declare maps through the Map interface and identify their generic key and value types.
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
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
Match common Map requirements with the correct method.
| Method | Description |
|---|---|
| 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
Trace insertion, retrieval, replacement, searching, removal, and size operations in one program.
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());
}
}Map: {101=Amit, 102=Neha, 103=Raj}
Student 102: Neha
Contains key 101: true
Contains Neha: true
Updated Map: {102=Neha, 103=Rahul}
Size: 2Check your understanding: After key 101 is removed, how many entries remain?
Two.
Step 7 of 15
5.7 HashMap
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
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);
}
}{null=Unknown, 101=Amit, 102=Neha, 103=Raj, 104=Neha}
After updating key 101: {null=Unknown, 101=Riya, 102=Neha, 103=Raj, 104=Neha}| Operation | Average complexity |
|---|---|
| put() | O(1) |
| get() | O(1) |
| remove() | O(1) |
| containsKey() | O(1) |
| Traversal | O(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
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
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);
}
}{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
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<Integer, String> students = new TreeMap<>();| Method | Description |
|---|---|
| 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
Use closest-match, endpoint, removal, and reverse-order navigation methods.
NavigableMap extends SortedMap and provides methods to locate the closest matching keys and entries.
| Method | Description |
|---|---|
| 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
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
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));
}
}{101=Amit, 102=Neha, 103=Raj, 105=Riya}
First key: 101
Last key: 105
Lower key than 103: 102
Higher key than 103: 105TreeMap<Integer, String> students =
new TreeMap<>(Comparator.reverseOrder());| Operation | Complexity |
|---|---|
| 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
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
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));
}
}{103=Raj, 102=Neha, 101=Amit}
Student 102: NehaCheck 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
Traverse keys, values, and complete entries and select the most efficient view for the required data.
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());
}
}
}Keys:
101
102
103
Values:
Amit
Neha
Raj
Entries:
101 : Amit
102 : Neha
103 : Raj| Required data | View |
|---|---|
| Keys only | keySet() |
| Values only | values() |
| Keys and values together | entrySet() |
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
Read and update a single key-value association through Map.Entry.
| Method | Description |
|---|---|
| getKey() | Returns the key |
| getValue() | Returns the value |
| setValue(value) | Updates the value |
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);
}
}{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
Select the correct Map implementation from ordering, null handling, synchronization, and performance requirements.
| Feature | HashMap | LinkedHashMap | TreeMap | Hashtable |
|---|---|---|---|---|
| Key order | No guarantee | Insertion order | Sorted order | No guarantee |
| Duplicate keys | Not allowed | Not allowed | Not allowed | Not allowed |
| Duplicate values | Allowed | Allowed | Allowed | Allowed |
| null key | One allowed | One allowed | Normally not allowed | Not allowed |
| null values | Allowed | Allowed | Allowed | Not allowed |
| Synchronized | No | No | No | Yes |
| Performance | Fast average lookup | Slightly slower than HashMap | O(log n) key operations | Slower due to synchronization |
| Type | Modern | Modern | Modern | Legacy |
| Requirement | Recommended implementation |
|---|---|
| Fast general-purpose key lookup | HashMap |
| Insertion order must be preserved | LinkedHashMap |
| Sorted keys or range navigation | TreeMap |
| Maintaining older synchronized code | Hashtable; prefer modern concurrent alternatives for new code |
Check your understanding: Which implementation should be selected when keys must remain sorted?
TreeMap.