Open In App

SortedMap Interface in Java with Examples

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

The SortedMap interface is a subinterface of the java.util.Map interface in Java. It extends the Map interface to provide a total ordering of its elements, based on the natural order of its keys.

The main difference between a SortedMap and a regular Map is that the elements in a SortedMap are stored in a sorted order, whereas in a Map the elements are stored in an arbitrary order. The sorting order is determined by the natural order of the keys, which must implement the java.lang.Comparable interface, or by a Comparator passed to the SortedMap’s constructor.

Here’s an example of how to use the SortedMap interface:

Java




import java.util.SortedMap;
import java.util.TreeMap;
  
public class Main {
    public static void main(String[] args) {
        SortedMap<String, Integer> sortedMap = new TreeMap<>();
  
        // Adding elements to the sorted map
        sortedMap.put("A", 1);
        sortedMap.put("C", 3);
        sortedMap.put("B", 2);
  
        // Getting values from the sorted map
        int valueA = sortedMap.get("A");
        System.out.println("Value of A: " + valueA);
  
        // Removing elements from the sorted map
        sortedMap.remove("B");
  
        // Iterating over the elements of the sorted map
        for (String key : sortedMap.keySet()) {
            System.out.println("Key: " + key + ", Value: " + sortedMap.get(key));
        }
    }
}


Output

Value of A: 1
Key: A, Value: 1
Key: C, Value: 3

 

SortedMap in Java

The main characteristic of a SortedMap is that it orders the keys by their natural ordering, or by a specified comparator. So consider using a TreeMap when you want a map that satisfies the following criteria: 

  • null key or null value is not permitted.
  • The keys are sorted either by natural ordering or by a specified comparator.

Type Parameters:

  • K – the type of keys maintained by this map
  • V – the type of mapped values

The parent interface of SortedMap is Map<K, V>.  

The subInterfaces of SortedMap are ConcurrentNavigableMap<K, V>, NavigableMap<K, V>.

SortedMap is implemented by ConcurrentSkipListMap, TreeMap.

Declaration:

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

 Example:

Java




// Java code to demonstrate SortedMap Interface
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
  
public class SortedMapExample {
    public static void main(String[] args)
    {
        SortedMap<Integer, String> sm
            = new TreeMap<Integer, String>();
        sm.put(new Integer(2), "practice");
        sm.put(new Integer(3), "quiz");
        sm.put(new Integer(5), "code");
        sm.put(new Integer(4), "contribute");
        sm.put(new Integer(1), "geeksforgeeks");
        Set s = sm.entrySet();
  
        // Using iterator in SortedMap
        Iterator i = s.iterator();
  
        // Traversing map. Note that the traversal
        // produced sorted (by keys) output .
        while (i.hasNext()) {
            Map.Entry m = (Map.Entry)i.next();
  
            int key = (Integer)m.getKey();
            String value = (String)m.getValue();
  
            System.out.println("Key : " + key
                               + "  value : " + value);
        }
    }
}


Output

Key : 1  value : geeksforgeeks
Key : 2  value : practice
Key : 3  value : quiz
Key : 4  value : contribute
Key : 5  value : code

Creating SortedMap Objects

Since SortedMap is an interface, objects cannot be created of the type SortedMap. We always need a class that extends this list in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the SortedMap. This type-safe map can be defined as:

// Obj1, Obj2 are the type of the object to be stored in SortedMap

SortedMap<Obj1, Obj2> set = new TreeMap<Obj1, Obj2> ();

Performing Various Operations on SortedMap

Since SortedMap is an interface, it can be used only with a class that implements this interface. TreeMap is the class that implements the SortedMap interface. Now, let’s see how to perform a few frequently used operations on the TreeMap.

1. Adding Elements: In order to add an element to the SortedMap, we can use the put() method. However, the insertion order is not retained in the TreeMap. Internally, for every element, the keys are compared and sorted in ascending order.

Java




// Java program add the elements in the SortedMap
import java.io.*;
import java.util.*;
class GFG {
  
    // Main Method
    public static void main(String args[])
    {
        // Default Initialization of a
        // SortedMap
        SortedMap tm1 = new TreeMap();
  
        // Initialization of a SortedMap
        // using Generics
        SortedMap<Integer, String> tm2
            = new TreeMap<Integer, String>();
  
        // Inserting the Elements
        tm1.put(3, "Geeks");
        tm1.put(2, "For");
        tm1.put(1, "Geeks");
  
        tm2.put(new Integer(3), "Geeks");
        tm2.put(new Integer(2), "For");
        tm2.put(new Integer(1), "Geeks");
  
        System.out.println(tm1);
        System.out.println(tm2);
    }
}


Output

{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the SortedMap are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change.

Java




// Java program to change
// the elements in SortedMap
import java.io.*;
import java.util.*;
class GFG {
    
      // Main Method
    public static void main(String args[])
    {
        // Initialization of a SortedMap
        // using Generics
        SortedMap<Integer, String> tm
            = new TreeMap<Integer, String>();
  
        // Inserting the Elements
        tm.put(3, "Geeks");
        tm.put(2, "Geeks");
        tm.put(1, "Geeks");
  
        System.out.println(tm);
  
        tm.put(2, "For");
  
        System.out.println(tm);
    }
}


Output

{1=Geeks, 2=Geeks, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}

3. Removing Element: In order to remove an element from the SortedMap, we can use the remove() method. This method takes the key value and removes the mapping for the key from this SortedMap if it is present in the map.

Java




// Java program to remove the 
// elements from SortedMap
import java.io.*;
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String args[])
    {
        // Initialization of a SortedMap
        // using Generics
        SortedMap<Integer, String> tm
            = new TreeMap<Integer, String>();
  
        // Inserting the Elements
        tm.put(3, "Geeks");
        tm.put(2, "Geeks");
        tm.put(1, "Geeks");
        tm.put(4, "For");
  
        System.out.println(tm);
  
        tm.remove(4);
  
        System.out.println(tm);
    }
}


Output

{1=Geeks, 2=Geeks, 3=Geeks, 4=For}
{1=Geeks, 2=Geeks, 3=Geeks}

4. Iterating through the SortedMap: There are multiple ways to iterate through the Map. The most famous way is to use an enhanced for loop and get the keys. The value of the key is found by using the getValue() method.

Java




// Java program to iterate through SortedMap
import java.util.*;
  
class GFG {
    
      // Main Method
    public static void main(String args[])
    {
        // Initialization of a SortedMap
        // using Generics
        SortedMap<Integer, String> tm
            = new TreeMap<Integer, String>();
  
        // Inserting the Elements
        tm.put(3, "Geeks");
        tm.put(2, "For");
        tm.put(1, "Geeks");
  
        for (Map.Entry mapElement : tm.entrySet()) {
            int key = (int)mapElement.getKey();
  
            // Finding the value
            String value = (String)mapElement.getValue();
  
            System.out.println(key + " : " + value);
        }
    }
}


Output

1 : Geeks
2 : For
3 : Geeks

The class which implements the SortedMap interface is TreeMap.

TreeMap class which is implemented in the collections framework is an implementation of the SortedMap Interface and SortedMap extends Map Interface. It behaves like a simple map with the exception that it stores keys in a sorted format. TreeMap uses a tree data structure for storage. Objects are stored in sorted, ascending order. But we can also store in descending order by passing a comparator. Let’s see how to create a SortedMap object using this class.

Java




// Java program to demonstrate the
// creation of SortedMap object using
// the TreeMap class
  
import java.util.*;
  
class GFG {
  
    public static void main(String[] args)
    {
        SortedMap<String, String> tm
            = new TreeMap<String, String>(new Comparator<String>() {
                  public int compare(String a, String b)
                  {
                      return b.compareTo(a);
                  }
              });
  
        // Adding elements into the TreeMap
        // using put()
        tm.put("India", "1");
        tm.put("Australia", "2");
        tm.put("South Africa", "3");
  
        // Displaying the TreeMap
        System.out.println(tm);
  
        // Removing items from TreeMap
        // using remove()
        tm.remove("Australia");
        System.out.println("Map after removing "
                           + "Australia:" + tm);
    }
}


Output

{South Africa=3, India=1, Australia=2}
Map after removing Australia:{South Africa=3, India=1}

Methods of SortedMap Interface

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

Methods inherited from interface java.util.Map

METHOD DESCRIPTION
clear()  This method is used to clear and remove all of the elements or mappings from a specified Map collection.
containsKey(Object)

This method is used to check whether a particular key is being mapped into the Map or not.

 It takes the key element as a parameter and returns True if that element is mapped in the map.

containsValue(Object) 

This method is used to check whether a particular value is being mapped by a single or more than one key in the Map. 

It takes the value as a parameter and returns True if that value is mapped by any of the key in the map.

entrySet() This method is used to create a set out of the same elements contained in the map. It basically returns a set view of the map or we can create a new set and store the map elements into them.
equals(Object) This method is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not.
get(Object) This method is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
hashCode() This method is used to generate a hashCode for the given map containing key and values.
isEmpty() This method is used to check if a map is having any entry for key and value pairs. If no mapping exists, then this returns true.
keySet() This method is used to return a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
put(Object, Object) This method is used to associate the specified value with the specified key in this map.
putAll(Map) This method is used to copy all of the mappings from the specified map to this map.
remove(Object) This method is used to remove the mapping for a key from this map if it is present in the map.
size() This method is used to return the number of key/value pairs available in the map.
values() This method is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the HashMap.

Advantages of SortedMap:

  1. Sorted order: The SortedMap interface provides a sorted order of its elements, based on the natural order of its keys or a custom Comparator passed to the constructor. This makes it useful in situations where you need to retrieve elements in a specific order.
  2. Predictable iteration order: Because the elements in a SortedMap are stored in a sorted order, you can predict the order in which they will be returned during iteration, making it easier to write algorithms that process the elements in a specific order.
  3. Search performance: The SortedMap interface provides an efficient implementation of the Map interface, allowing you to retrieve elements in logarithmic time, making it useful in search algorithms where you need to retrieve elements quickly.

Disadvantages of SortedMap:

  1. Slow for inserting elements: Inserting elements into a SortedMap can be slower than inserting elements into a regular Map, as the SortedMap needs to maintain the sorted order of its elements.
  2. Key restriction: The keys in a SortedMap must implement the java.lang.Comparable interface or a custom Comparator must be provided. This can be a restriction if you need to use custom keys that do not implement this interface.

Reference books:

  1. “Java Collections” by Maurice Naftalin and Philip Wadler. This book provides a comprehensive overview of the Java Collections framework, including the SortedMap interface.
  2. “Java in a Nutshell” by David Flanagan. This book provides a quick reference for the core features of Java, including the SortedMap interface.
  3. “Java Generics and Collections” by Maurice Naftalin and Philip Wadler. This book provides a comprehensive guide to generics and collections in Java, including the SortedMap interface.
     


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads