Course contentsShow
← Java
Lesson 1000 of 2,87023. Collections Framework OverviewFree lesson

TreeMap: When to Use It

Identify use cases needing sorted keys, range operations, floor/ceiling lookups, or naturally ordered key-value pairs.

TreeMap: When to Use It

What you'll learn: You'll discover the specific scenarios where TreeMap is the best choice among Java's Map implementations.

When TreeMap Shines

You've learned that TreeMap maintains keys in sorted order using a red-black tree. But when should you actually choose it over HashMap? The answer lies in whether you need specific ordering or navigation features that HashMap simply cannot provide.

Key Use Cases for TreeMap

1. Sorted Key Iteration

When you need to process keys in their natural order (or a custom Comparator order), TreeMap automatically keeps them sorted. Imagine a phone book application—you want names displayed alphabetically without manually sorting.

2. Range Operations

TreeMap excels when you need subsets of your data:

  • All keys between two values
  • All entries less than or greater than a threshold
  • First or last entries in sorted order

3. Floor and Ceiling Lookups

Need the "closest match" to a key that might not exist? TreeMap provides methods to find the greatest key less than or equal to your target (floor), or the least key greater than or equal to it (ceiling). Think of finding the nearest store location based on distance codes.

4. Naturally Ordered Key-Value Pairs

When your domain inherently requires ordered keys—timestamps, priority levels, alphabetical indexes—TreeMap maintains that order automatically with every insertion and removal.

When NOT to Use TreeMap

If you only need fast lookups without caring about order, stick with HashMap. TreeMap's O(log n) operations are slower than HashMap's O(1) average case.

Key Takeaway: Choose TreeMap when you need sorted keys, range queries, or navigational operations like floor/ceiling lookups—not for raw speed alone.