0
0
JavaComparisonBeginner · 4 min read

HashMap vs TreeMap vs LinkedHashMap in Java: Key Differences and Usage

In Java, HashMap stores key-value pairs with no order and offers fast access, TreeMap keeps keys sorted naturally or by a comparator, and LinkedHashMap maintains insertion order with a linked list. Choose HashMap for speed, TreeMap for sorted keys, and LinkedHashMap when order matters.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of HashMap, TreeMap, and LinkedHashMap based on key factors.

FeatureHashMapTreeMapLinkedHashMap
OrderingNo order (random)Sorted by keys (natural or comparator)Insertion order
Performance (get/put)O(1) averageO(log n)O(1) average
Null keys allowedYes (one null key)NoYes (one null key)
ImplementationHash tableRed-Black treeHash table + doubly linked list
Use caseFast access without orderSorted map neededOrder of insertion matters
⚖️

Key Differences

HashMap uses a hash table to store entries, so it provides very fast access and insertion but does not guarantee any order of keys. It allows one null key and multiple null values.

TreeMap stores entries in a red-black tree structure, which keeps keys sorted either by their natural order or a custom comparator. This makes operations slower (logarithmic time) but useful when sorted data is required. It does not allow null keys because sorting null is undefined.

LinkedHashMap combines a hash table with a doubly linked list to maintain the order in which entries were inserted. It offers similar performance to HashMap but preserves insertion order, making it ideal when order matters but sorting is not needed. It also allows one null key.

⚖️

Code Comparison

This example shows how to add and print entries using HashMap.

java
import java.util.HashMap;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("apple", 3);
        map.put("banana", 2);
        map.put("orange", 5);

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}
Output
banana = 2 orange = 5 apple = 3
↔️

TreeMap Equivalent

This example shows the same task using TreeMap, which prints entries sorted by key.

java
import java.util.Map;
import java.util.TreeMap;

public class TreeMapExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<>();
        map.put("apple", 3);
        map.put("banana", 2);
        map.put("orange", 5);

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}
Output
apple = 3 banana = 2 orange = 5
🎯

When to Use Which

Choose HashMap when you need the fastest access and don't care about order. Use TreeMap when you need keys sorted automatically, such as for range queries or ordered iteration. Pick LinkedHashMap when you want to preserve the order of insertion, like caching or predictable iteration order.

Key Takeaways

Use HashMap for fast, unordered key-value storage with null key support.
Use TreeMap when you need keys sorted and don't allow null keys.
Use LinkedHashMap to maintain insertion order with fast access.
TreeMap operations are slower due to sorting but useful for ordered data.
Choose the map type based on whether order, sorting, or speed matters most.