0Pricing
Java Academy · Lesson

Custom Ordering in Tree Collections

Supply a Comparator to TreeMap/TreeSet to define domain-specific sort orders.

Why Custom Ordering?

Tree collections (TreeMap, TreeSet) use natural ordering by default. When your domain objects don't have a natural order, or you need a different sort, you supply a Comparator at construction time.

Comparator at TreeMap Construction

Pass a comparator to sort keys by a custom rule — for example, reverse alphabetical order:

import java.util.*;

TreeMap<String, Integer> map = new TreeMap<>(Comparator.reverseOrder());
map.put("banana", 2);
map.put("apple", 1);
map.put("cherry", 3);

map.forEach((k,v) -> System.out.println(k)); // cherry, banana, apple

All lessons in this course

  1. TreeMap: Sorted Key-Value Pairs
  2. Submaps and Range Views
  3. TreeSet and NavigableSet
  4. Custom Ordering in Tree Collections
← Back to Java Academy