What is the difference between HashMap and TreeMap?

HashMap and TreeMap are both implementations of the Map interface used to store key-value pairs. The main difference is that HashMap stores entries without maintaining any order, while TreeMap automatically keeps entries sorted based on their keys. HashMap generally offers faster performance, whereas TreeMap is preferred when sorted data is required.

Key Points

Internal Implementation

HashMap

TreeMap

Ordering

HashMap

No ordering guarantee.

Example

{103=Mike, 101=John, 102=David}

Output order may vary.

TreeMap

Automatically sorts keys.

Example

{101=John, 102=David, 103=Mike}

Time Complexity

HashMap

TreeMap

Null Handling

HashMap

TreeMap

Example

HashMap<String, String> map =
        new HashMap<>();

map.put(null, "Java");

Valid.

TreeMap<String, String> map =
        new TreeMap<>();

map.put(null, "Java");

Throws NullPointerException.

Sorting Support

HashMap

TreeMap

Example

Suppose we are storing employee records.

If ordering is not important

Use HashMap.

If records must be displayed in ascending employee ID order

Use TreeMap.

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

public class Demo {

    public static void main(String[] args) {

        Map<Integer, String> hashMap =
                new HashMap<>();

        hashMap.put(103, "Mike");
        hashMap.put(101, "John");
        hashMap.put(102, "David");

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

        treeMap.put(103, "Mike");
        treeMap.put(101, "John");
        treeMap.put(102, "David");

        System.out.println(hashMap);

        System.out.println(treeMap);
    }
}

Output

HashMap

Order not guaranteed

TreeMap

{101=John, 102=David, 103=Mike}

When to Use HashMap?

Examples

When to Use TreeMap?

Examples

Comparison Table

Feature HashMap TreeMap

Ordering No Sorted by Key

Internal Structure Hash Table Red-Black Tree

Insertion O(1) O(log n)

Retrieval O(1) O(log n)

Deletion O(1) O(log n)

Null Key One Allowed Not Allowed

Null Values Allowed Allowed

Sorting Support No Yes

Interview Tip

A concise interview answer is

HashMap stores key-value pairs without maintaining any order and provides O(1) average-time performance using hashing. TreeMap stores entries in sorted key order using a Red-Black Tree and provides O(log n) performance for insertion, retrieval, and deletion. Use HashMap when speed is important and TreeMap when sorted data is required.

Last updated: 11 November 2026

Previous question: How do you choose the appropriate design pattern for a particular problem in Java?

Next question: When would you use a TreeMap instead of a HashMap?

More Core Java - Level II interview questions

All Core Java - Level II questions