interface SortedMap Tutorial

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

public interface SortedMap extends Map
Following are the important methods:

  1. Comparator comparator(): Used to change the order of elements as per the client requirements (the default order is ascending).
  2. Object firstKey(): Returns the first key added. Returns null if the map does not contain any elements; here elements are key/value pairs.
  3. Object lastKey(): Returns the last key added. Returns null if the map does not contain any elements.
  4. 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.
  5. SortedMap headMap(Object key1): Returns a sorted map that contains all the keys less than key1.
  6. SortedMap tailMap(Object key2): Returns a sorted map that contains all the keys greater than or equal to key2.

Leave a Comment

Your email address will not be published.