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, appleAll lessons in this course
- TreeMap: Sorted Key-Value Pairs
- Submaps and Range Views
- TreeSet and NavigableSet
- Custom Ordering in Tree Collections