Course contentsShow
← Java
Lesson 1133 of 2,87026. Map ImplementationsFree lesson

Creating TreeMaps with Natural Ordering

Instantiating TreeMaps where keys implement Comparable, relying on their natural ordering.

Creating TreeMaps with Natural Ordering

What you'll learn: How to instantiate a TreeMap that automatically sorts entries by their keys using the keys' natural ordering.


The Core Idea

When you create a TreeMap without specifying a custom comparator, it relies on the natural ordering of its keys. This means the keys must implement the Comparable interface, and the TreeMap will use their compareTo() method to maintain sorted order.

Think of it like organizing a phone book: names are automatically sorted alphabetically because strings have a natural alphabetical ordering built in. The TreeMap acts as your automatic organizer, keeping everything in order as you add entries.

How to Create a TreeMap with Natural Ordering

import java.util.TreeMap;

// Keys must implement Comparable
TreeMap<Integer, String> ageMap = new TreeMap<>();
ageMap.put(25, "Alice");
ageMap.put(30, "Bob");
ageMap.put(20, "Charlie");

// Iteration is automatically sorted by key
for (Integer age : ageMap.keySet()) {
    System.out.println(age + ": " + ageMap.get(age));
}
// Output:
// 20: Charlie
// 25: Alice
// 30: Bob

The empty TreeMap<>() constructor tells Java: "Use the keys' natural ordering." Since Integer implements Comparable<Integer>, the map automatically sorts numerically.

What Qualifies as Natural Ordering

Common types with natural ordering include:

  • Integer, Long, Double: Numerical order
  • String: Lexicographical (dictionary) order
  • LocalDate, LocalDateTime: Chronological order

If your key type doesn't implement Comparable, you'll get a ClassCastException at runtime when you try to add the second element.

Key Takeaway: Creating a TreeMap with new TreeMap<>() automatically sorts entries by key using the keys' natural ordering, provided the key type implements Comparable.