Introduction
In Java, the Map interface is widely used for storing key-value pairs. But when choosing a specific implementation—HashMap, LinkedHashMap, or TreeMap—it can be confusing because they all store data in a similar way. However, they differ in ordering, internal working, performance, and use cases. This article explains each map type in simple, natural language along with code examples so you can easily understand when to use each one.
1. HashMap in Java
HashMap is the most commonly used map implementation. It stores data in no particular order.
Key Features
Does not maintain any order of keys.
Allows one null key and multiple null values.
Fast performance for basic operations: O(1) average time.
Uses hashing internally to store data.
Example
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(3, "Apple");
map.put(1, "Mango");
map.put(2, "Banana");
System.out.println(map); // Output: Order is unpredictable
}
}
When to Use HashMap
When you do NOT care about key ordering.
When you need fast lookups, inserts, and deletions.
For most general-purpose applications.
2. LinkedHashMap in Java
LinkedHashMap maintains the insertion order of elements. It works like HashMap but keeps a doubly-linked list internally.
Key Features
Maintains insertion order.
Slightly slower than HashMap due to ordering overhead.
Supports one null key and multiple null values.
Useful when predictable ordering is needed.
Example
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(3, "Apple");
map.put(1, "Mango");
map.put(2, "Banana");
System.out.println(map); // Output: {3=Apple, 1=Mango, 2=Banana}
}
}
When to Use LinkedHashMap
When order matters.
When building caches or predictable-iteration systems.
When you want HashMap features + ordering.
3. TreeMap in Java
TreeMap stores keys in sorted (ascending) order. It uses a Red-Black Tree internally.
Key Features
Automatically sorts keys.
Does NOT allow null keys (throws NullPointerException).
Slower than HashMap and LinkedHashMap.
Provides consistent ordering.
Example
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "Apple");
map.put(1, "Mango");
map.put(2, "Banana");
System.out.println(map); // Output: {1=Mango, 2=Banana, 3=Apple}
}
}
When to Use TreeMap
When you need data in sorted order.
When working with ranges (e.g.,
headMap,tailMap,subMap).When predictable sorting is essential.
Key Differences Between HashMap, LinkedHashMap, and TreeMap
1. Ordering
Join the conversation! Your thoughts help the community grow.