HashMap vs TreeMap in Java

In this post, we will learn the difference between HashMap andTreeMap in Java. This is a frequently asked question in Java interviews for beginners. Let's dive into it.

Difference between HashMap and TreeMap in Java

HashMap TreeMap
HashMap implements the Map interface. TreeMap also implements the Map interface.
HashMap doesn't maintain any order. The elements are not ordered. TreeMap stores keys in sorted order (it's a sorted map). The elements are ordered by the natural ordering of keys or by a custom Comparator provided at map creation time.
HashMap allows one null key and multiple null values. TreeMap doesn't allow null keys but can have multiple null values. If you try to insert a null key, it will throw a NullPointerException.
HashMap provides constant-time performance for basic operations like get and put, assuming the hash function disperses the elements properly among the buckets. TreeMap provides guaranteed log(n) time cost for the containsKey, get, put, and remove operations because it is implemented as a Red-Black tree.
HashMap is typically faster than TreeMap. It is a good choice when you don't care about the order of elements. TreeMap is slower than HashMap. It's a good choice when you need to keep all entries in natural order.
In HashMap, operations like add, remove, containsKey, etc. have a constant time complexity O(1). In TreeMap, operations like add, remove, containsKey, etc. have a time complexity of O(log(n)).
HashMap is a better choice when you need efficient access and insertion of key/value pairs. TreeMap is a better choice when you need elements to be sorted or need to use functionalities like higherKey, lowerKey, etc.

Example

Let's create an example to illustrate the difference between HashMap and TreeMap in Java. 

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

public class HashMapVsTreeMapExample {
    public static void main(String[] args) {
        // Example using HashMap
        Map<String, Integer> hashMap = new HashMap<>();

        hashMap.put("John", 25);
        hashMap.put("Alice", 30);
        hashMap.put("Bob", 22);

        System.out.println("HashMap:");
        for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        // Example using TreeMap
        Map<String, Integer> treeMap = new TreeMap<>();

        treeMap.put("John", 25);
        treeMap.put("Alice", 30);
        treeMap.put("Bob", 22);

        System.out.println("\nTreeMap:");
        for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output:

HashMap:
Alice: 30
Bob: 22
John: 25

TreeMap:
Alice: 30
Bob: 22
John: 25

Explanation: 

As you can see from the output, the order of elements in the HashMap is not maintained, while the elements in the TreeMap are sorted based on the keys in ascending order. 

Keep in mind that TreeMap is slightly slower than HashMap for most operations due to its sorted nature. However, if you need to maintain the elements in sorted order based on keys, TreeMap is a better choice. If you don't need a specific order, HashMap provides better performance for most scenarios.

Download Cheat Sheet:


Comments