As you can observe in the collections framework hierarchy, the Map interface comes with another sub interface SortedMap. The SortedMap can make use of all the methods of Map interface and also it adds its own (the list is given hereunder). The extra advantage (the original one is unique keys, a feature derived from its super interface, Map) of SortedMap is it returns the elements in ascending order by default. The sorting is performed on keys (but not on values). The order can be changed or customized using Comparator interface.
One important implementation (subclass) is TreeMap. SortedMap provides methods (headMap() and tailMap()) to get a few key/value pairs from the map satisfying some condition. A subMap() method is used to extract a few key/value pairs from a map that do not satisfy any condition; read the methods down.
Following is the interface signature
- Comparator comparator(): Used to change the order of elements as per the client requirements (the default order is ascending).
- Object firstKey(): Returns the first key added. Returns null if the map does not contain any elements; here elements are key/value pairs.
- Object lastKey(): Returns the last key added. Returns null if the map does not contain any elements.
- SortedMap subMap(int startKey, int endKey): Returns a SortedMap that includes all the elements of the map, starting from startKey to endKey-1, an easy way to extract a part of a sorted map.
- SortedMap headMap(Object key1): Returns a sorted map that contains all the keys less than key1.
- SortedMap tailMap(Object key2): Returns a sorted map that contains all the keys greater than or equal to key2.