✅ MAP in Java
1. What is Map in Java?
Map in Java is part of the Java Collections Framework.
It stores key-value pairs (also called entries).
Each key is unique, but values can be duplicated.
Keys cannot be null in some implementations (e.g., TreeMap), but HashMap allows
one null key.
Order of elements depends on the implementation.
Key Characteristics of Map
Keys → Unique
Values → Can be duplicated
Implementations: HashMap, LinkedHashMap, TreeMap
2. Types of Map in Java
(a) HashMap
Unordered collection of key-value pairs.
Based on Hashing.
Allows 1 null key and multiple null values.
Time Complexity:
o put() / get() → O(1) average case
Not Thread-Safe.
Syntax:
Map<KeyType, ValueType> map = new HashMap<>();
(b) LinkedHashMap
Maintains insertion order.
Slower than HashMap.
Allows null keys and null values.
Syntax:
Map<KeyType, ValueType> map = new LinkedHashMap<>();
(c) TreeMap
Sorted map (natural order of keys or custom comparator).
Does not allow null keys.
Based on Red-Black Tree.
Operations: O(log n)
Syntax:
Map<KeyType, ValueType> map = new TreeMap<>();
3. Common Operations on Map
Operation Method Example
Insert map.put(key, value)
Access Value map.get(key)
Check Key Exists map.containsKey(key)
Check Value Exists map.containsValue(value)
Remove map.remove(key)
Size map.size()
Iterate Keys map.keySet()
Iterate Values map.values()
Iterate Entries map.entrySet()
4. Java Examples with Output
Example 1: HashMap
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
// Adding elements
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Orange");
// Display Map
System.out.println("HashMap: " + map);
// Access value
System.out.println("Value for key 2: " + map.get(2));
// Check key exists
System.out.println("Contains key 3? " + map.containsKey(3));
// Remove key
map.remove(1);
System.out.println("After removal: " + map);
}
}
Output:
HashMap: {1=Apple, 2=Banana, 3=Orange}
Value for key 2: Banana
Contains key 3? true
After removal: {2=Banana, 3=Orange}
Example 2: LinkedHashMap
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new LinkedHashMap<>();
map.put("A", 100);
map.put("B", 200);
map.put("C", 300);
System.out.println("LinkedHashMap: " + map);
}
}
Output:
LinkedHashMap: {A=100, B=200, C=300}
Example 3: TreeMap
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new TreeMap<>();
map.put(10, "Dog");
map.put(5, "Cat");
map.put(15, "Horse");
System.out.println("TreeMap: " + map);
}
}
Output:
TreeMap: {5=Cat, 10=Dog, 15=Horse}