Map in Java Collection Framework – Complete Guide with Examples
- What is a Map in Java?
- Real-world Analogy:
- Basic Syntax
- Key Characteristics of Map:
- Implementations of Map Interface
- 1. HashMap – Most Commonly Used Map
- Features:
- Example:
- 2. LinkedHashMap – Maintains Insertion Order
- Features:
- Example:
- 3. TreeMap – Sorted Map
- Features:
- Example:
- 4. Hashtable – Legacy Synchronized Map
- Features:
- Example:
- 5. ConcurrentHashMap – Thread-safe and Fast
- Features:
- Common Map Methods
- Example with Multiple Methods:
- Example Code Explanation: Using Map Methods
- Summary of Map Methods Used:
- Map vs Collection
- Iterating through a Map
- Using entrySet() and for-each loop:
- Using keySet():
- Best Practices
- Conclusion
- Summary Table
In Java, the Collection Framework is a powerful tool that allows developers to store, manipulate, and retrieve data efficiently. While most collections like List, Set, and Queue store individual elements, the Map interface is unique, it stores data in the form of key-value pairs.
In this tutorial, we will learn every important detail about Map in Java, suitable for beginners and intermediate learners. We’ll break everything down in simple terms and explain with real-world examples.
What is a Map in Java?
In Java, a Map is an object that maps unique keys to corresponding values. It is part of the Java Collection Framework, but unlike List or Set, it does not extend the Collection interface.
We can also define it as, In Java, Map is an interface from the java.util package. It defines the behavior of a mapping data structure, and like all interfaces in Java, it can be used as a type for objects that implement it.
Instead, Map is a separate interface that models a key-value pair data structure—also known as an associative array or dictionary in other programming languages.
Real-world Analogy:
Think of a Map like a dictionary:
- The word is the key
- The definition is the value
You can’t have the same word (key) twice in a dictionary, but you can have multiple words with the same definition (value).
Basic Syntax
Map<KeyType, ValueType> mapName = new HashMap<>();
Here, KeyType and ValueType are data types of keys and values, respectively.
Key Characteristics of Map:
| Feature | Description |
|---|---|
| Duplicates in Keys | ❌ Not Allowed |
| Duplicates in Values | ✅ Allowed |
| Null Keys | ✅ Only one null key allowed in HashMap |
| Null Values | ✅ Multiple null values are allowed |
Implementations of Map Interface
Java provides several classes that implement the Map interface:
| Class Name | Description |
|---|---|
HashMap | Fast, unordered map using hashing |
LinkedHashMap | Maintains insertion order |
TreeMap | Maintains natural sorted order of keys |
Hashtable | Legacy class, synchronized |
ConcurrentHashMap | Thread-safe version of HashMap |
Let’s explore them one by one.
1. HashMap – Most Commonly Used Map
Features:
- Allows one
nullkey and multiplenullvalues - Not thread-safe
- Does not maintain any order
Example:
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
Map<String, String> capitalMap = new HashMap<>();
capitalMap.put("India", "New Delhi");
capitalMap.put("USA", "Washington D.C.");
capitalMap.put("Japan", "Tokyo");
System.out.println(capitalMap);
}
}
Output:
{Japan=Tokyo, USA=Washington D.C., India=New Delhi}
Note: The order may change as HashMap doesn’t guarantee order.
2. LinkedHashMap – Maintains Insertion Order
Features:
- Keeps the order of keys as inserted
- Slower than
HashMap, but predictable iteration order
Example:
import java.util.*;
public class LinkedHashMapExample {
public static void main(String[] args) {
Map<String, Integer> marks = new LinkedHashMap<>();
marks.put("Math", 90);
marks.put("Science", 85);
marks.put("English", 92);
System.out.println(marks);
}
}
Output:
{Math=90, Science=85, English=92}
3. TreeMap – Sorted Map
Features:
- Automatically sorts keys in natural order (ascending for numbers and alphabetic for strings)
- Does not allow
nullkeys
Example:
import java.util.*;
public class TreeMapExample {
public static void main(String[] args) {
Map<Integer, String> tree = new TreeMap<>();
tree.put(3, "Three");
tree.put(1, "One");
tree.put(2, "Two");
System.out.println(tree);
}
}
Output:
{1=One, 2=Two, 3=Three}
4. Hashtable – Legacy Synchronized Map
Features:
- Thread-safe
- Slower due to synchronization
- Doesn’t allow
nullkeys ornullvalues
Example:
import java.util.*;
public class HashtableExample {
public static void main(String[] args) {
Map<String, String> table = new Hashtable<>();
table.put("A", "Apple");
table.put("B", "Banana");
System.out.println(table);
}
}
Output
{A=Apple, B=Banana}
5. ConcurrentHashMap – Thread-safe and Fast
Features:
- Used in multithreading environments
- Better performance than
Hashtable - Doesn’t allow
nullkeys ornullvalues
import java.util.concurrent.*;
public class ConcurrentHashMapExample {
public static void main(String[] args) {
ConcurrentMap<String, Integer> cmap = new ConcurrentHashMap<>();
cmap.put("Java", 90);
cmap.put("Python", 95);
System.out.println(cmap);
}
}
Output
{Java=90, Python=95}
Common Map Methods
| Method | Description |
|---|---|
put(key, value) | Adds key-value pair |
get(key) | Returns the value associated with the key |
remove(key) | Removes entry with the given key |
containsKey(key) | Checks if key exists |
containsValue(value) | Checks if value exists |
keySet() | Returns a set of all keys |
values() | Returns a collection of all values |
entrySet() | Returns a set of all key-value pairs |
Example with Multiple Methods:
import java.util.*;
public class MapMethodsDemo {
public static void main(String[] args) {
Map<String, String> student = new HashMap<>();
student.put("name", "John");
student.put("age", "21");
student.put("course", "B.Tech");
System.out.println("Name: " + student.get("name"));
System.out.println("Contains key 'age'? " + student.containsKey("age"));
System.out.println("All keys: " + student.keySet());
System.out.println("All values: " + student.values());
System.out.println("All entries: " + student.entrySet());
}
}
Example Code Explanation: Using Map Methods
Map<String, String> student = new HashMap<>();
import java.util.*;
public class MapMethodsDemo {
public static void main(String[] args) {
Map<String, String> student = new HashMap<>();
Here, we’re creating a Map object named student.
- It uses
Stringfor both keys and values. HashMapis the implementation being used (fast and allows onenullkey).
put(key, value)
student.put("name", "John");
student.put("age", "21");
student.put("course", "B.Tech");
- Adds a key-value pair to the map.
- If the key already exists, its value is replaced.
Internally, the map now looks like this:
{
"name": "John",
"age": "21",
"course": "B.Tech"
}
get(key)
System.out.println("Name: " + student.get("name"));
- Retrieves the value associated with the given key.
- In this case, it prints:
Name: John
containsKey(key)
System.out.println("Contains key 'age'? " + student.containsKey("age"));
- Checks if the given key exists in the map.
- Returns
truefor"age"since it is present.
keySet()
System.out.println("All keys: " + student.keySet());
- Returns a
Setof all keys in the map. - Output:
[name, age, course](order may vary)
values()
System.out.println("All values: " + student.values());
- Returns a
Collectionof all values stored in the map. - Output:
[John, 21, B.Tech](order may vary)
entrySet()
System.out.println("All entries: " + student.entrySet());
- Returns a
Setof all key-value pairs asMap.Entryobjects. - Output example:
[name=John, age=21, course=B.Tech]
Each entry here is like:
Map.Entry<String, String>
Summary of Map Methods Used:
| Method | Purpose |
|---|---|
put(k, v) | Adds or updates a key-value pair |
get(k) | Fetches value for the given key |
containsKey(k) | Checks if the key exists |
keySet() | Returns all keys |
values() | Returns all values |
entrySet() | Returns all key-value pairs |
Map vs Collection
| Feature | Map | Collection (List/Set/Queue) |
|---|---|---|
| Stores | Key-value pairs | Single elements |
| Allows duplicate | No (keys) | Yes (List), No (Set) |
| Examples | HashMap, TreeMap | ArrayList, HashSet, Queue |
Iterating through a Map
Using entrySet() and for-each loop:
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
Using keySet():
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
Best Practices
- Use HashMap for fast, general-purpose usage.
- Use LinkedHashMap when order of insertion matters.
- Use TreeMap for sorted keys.
- Avoid using
nullkeys unless usingHashMap. - Use ConcurrentHashMap in multithreaded applications.
Conclusion
The Map interface in Java is extremely powerful when it comes to mapping relationships between data. It is a must-have tool for any serious Java developer. Whether you are building a simple student database, a dictionary, or a configuration system, understanding how different types of maps work will make your code cleaner and more efficient.
Summary Table
| Map Type | Allows Null Key | Maintains Order | Sorted | Thread-Safe |
|---|---|---|---|---|
HashMap | ✅ Yes (one) | ❌ No | ❌ No | ❌ No |
LinkedHashMap | ✅ Yes (one) | ✅ Yes | ❌ No | ❌ No |
TreeMap | ❌ No | ✅ Yes (Sorted) | ✅ Yes | ❌ No |
Hashtable | ❌ No | ❌ No | ❌ No | ✅ Yes |
ConcurrentHashMap | ❌ No | ❌ No | ❌ No | ✅ Yes |
If you’re learning Java Collections, mastering Map and its implementations is essential. It’s used in real-world applications like caching, storing database records, managing key-value configurations, and much more.