dsa

Java SortedMap Interface

In this tutorial, we will learn about the Java SortedMap interface and its methods.

SortedMap is an interface in collection framework. This interface extends Map interface and provides a total ordering of its elements (elements can be traversed in sorted order of keys). Exampled class that implements this interface is TreeMap.

The SortedMap interface extends Map. It ensures that the entries are maintained in an ascending key order. Several methods throw a NoSuchElementException when no items are in the invoking map. A ClassCastException is thrown when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object when null is not allowed in the map.

sorted map

Methods of SortedMap

  • subMap(K fromKey, K toKey): Returns a view of the portion of this Map whose keys range from fromKey, inclusive, to toKey, exclusive.
  • headMap(K toKey): Returns a view of the portion of this Map whose keys are strictly less than toKey.
  • tailMap(K fromKey): Returns a view of the portion of this Map whose keys are greater than or equal to fromKey.
  • firstKey(): Returns the first (lowest) key currently in this Map.
  • lastKey(): Returns the last (highest) key currently in this Map.
  • comparator(): Returns the Comparator used to order the keys in this Map, or null if this Map uses the natural ordering of its keys.
  • values(): Returns a Collection view of the values contained in this map.
  • keySet(): Returns a Set view of the keys contained in this map.
  • entrySet(): Returns a Set view of the mappings contained in this map.
  • Code for SortedMap

    public interface SortedMap extends Map
    {
        Comparator comparator();
        SortedMap subMap(K fromKey, K toKey);
        SortedMap headMap(K toKey);
        SortedMap tailMap(K fromKey);
        K firstKey();
        K lastKey();
    }