11.6. Sorted Sets and Sorted Maps
Sets and maps have special interfaces, called SortedSet and SortedMap, for implementations that sort their elements in a specific order (see Figures 11.2 and 11.3). Objects can specify their natural order by implementing the Comparable interface, or be dictated a total order by a comparator object that implements the Comparator interface.
We'll first look at the two interfaces Comparable and Comparator, before discussing sorted sets and maps.
The Comparator Interface
Precise control of ordering can be achieved by creating a customized comparator that imposes a specific total ordering on the elements. All comparators implement the Comparator interface, which has the following single method:
int compare(Object ...
Get Programmer's Guide to Java™ Certification, A: A Comprehensive Primer, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.