ASortedMap
is aMap
that maintains its entries in ascending order, sorted according to the keys' natural ordering, or according to aComparator
provided at the time of theSortedMap
creation. Natural ordering andComparator
s are discussed in the Object Ordering section. TheSortedMap
interface provides operations for normalMap
operations and for the following:The following interface is the
Range view
performs arbitrary range operations on the sorted mapEndpoints
returns the first or the last key in the sorted mapComparator access
returns theComparator
, if any, used to sort the mapMap
analog ofSortedSet
.public interface SortedMap<K, V> extends Map<K, V>{ Comparator<? super K> comparator(); SortedMap<K, V> subMap(K fromKey, K toKey); SortedMap<K, V> headMap(K toKey); SortedMap<K, V> tailMap(K fromKey); K firstKey(); K lastKey(); }
The operationsSortedMap
inherits fromMap
behave identically on sorted maps and normal maps with two exceptions:Although it isn't guaranteed by the interface, the
- The
Iterator
returned by theiterator
operation on any of the sorted map'sCollection
views traverse the collections in order.- The arrays returned by the
Collection
views'toArray
operations contain the keys, values, or entries in order.toString
method of theCollection
views in all the Java platform'sSortedMap
implementations returns a string containing all the elements of the view, in order.
By convention, all general-purposeMap
implementations provide a standard conversion constructor that takes aMap
;SortedMap
implementations are no exception. InTreeMap
, this constructor creates an instance that orders its entries according to their keys' natural ordering. This was probably a mistake. It would have been better to check dynamically to see whether the specifiedMap
instance was aSortedMap
, and if so, to sort the new map according to the same criterion (comparator or natural ordering). BecauseTreeMap
took the approach it did, it also provides a constructor that takes aSortedMap
and returns a newTreeMap
containing the same mappings as the givenSortedMap
, sorted according to the same criterion. Note that it is the compile-time type of the argument, not its runtime type, that determines whether theSortedMap
constructor is invoked in preference to the ordinarymap
constructor.
SortedMap
implementations also provide, by convention, a constructor that takes aComparator
and returns an empty map sorted according to the specifiedComparator
. Ifnull
is passed to this constructor, it returns aMap
that sorts its mappings according to their keys' natural ordering.
Because this interface is a preciseMap
analog ofSortedSet
, all the idioms and code examples in The SortedSet Interface section apply toSortedMap
with only trivial modifications.