SortedMap Interface in Java
SortedMap is an interface in the collection framework that is a part of java.util package and extends the Map interface. It represents a map that maintains its keys in a sorted order. The keys in a SortedMap are sorted according to their natural ordering or by a Comparator provided at the time of map creation.
- SortedMap is a sub-interface of a map that ensures keys are stored in a sorted order.
- The primary class that implements SortedMap is TreeMap which maintains elements in a Red-Black tree structure to ensure sorting.
- A comparator can be passed to customize the sorting order of the keys.
- A SortedMap orders the keys by their natural ordering (if the key implements Comparable) or by a specified Comparator (if provided).
- SortedMap does not allow null keys or null values. If we insert a null key or value it will throw an error.
Example: This example demonstrates basic operation on a SortedMap using TreeMap.
// Java program to demonstartes
// basic operations on SortedMap
import java.util.SortedMap;
import java.util.TreeMap;
public class Geeks {
public static void main(String[] args)
{
SortedMap<String, Integer> s = new TreeMap<>();
// Adding elements to the sorted map
s.put("A", 1);
s.put("C", 3);
s.put("B", 2);
System.out.println("SortedMap: " + s);
// Getting values from the sorted map
int ans = s.get("A");
System.out.println("Value of A: " + ans);
// Removing elements from the sorted map
s.remove("B");
System.out.println(
"Updated SortedMap After removal:" + s);
}
}
Output
SortedMap: {A=1, B=2, C=3} Value of A: 1 Updated SortedMap After removal:{A=1, C=3}
SortedMap Hierarchy
The diagram illustrates the Map hierarchy, showing how different Map implementations (HashMap, TreeMap, LinkedHashMap) relate to the Map and SortedMap interfaces.

Declaration of SortedMap Interface
In Java, the declaration of SortedMap Interface can be done as:
public interface SortedMap<K, V> extends Map<K, V> {
// Method signatures for SortedMap
Comparator<? super K> comparator();
K firstKey();
K lastKey();
SortedMap<K, V> headMap(K toKey);
SortedMap<K, V> tailMap(K fromKey);
SortedMap<K, V> subMap(K fromKey, K toKey);
}
Example: This example demonstrates how to use a SortedMap to store and iterate over key-value pairs in sorted order based on the keys.
// Java Program to demonstrates
// how to use a SortedMap
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
public class Geeks {
public static void main(String[] args) {
// Create a SortedMap using TreeMap
SortedMap<Integer, String> sm = new TreeMap<>();
// Adding key-value pairs to the SortedMap
sm.put(2, "Java");
sm.put(3, "C++");
sm.put(1, "Python");
sm.put(4, "Js");
// Get entry set
Set<Map.Entry<Integer, String>> s = sm.entrySet();
// Using iterator to traverse the SortedMap
Iterator<Map.Entry<Integer, String>> i = s.iterator();
// Traversing the map (sorted by keys)
while (i.hasNext()) {
Map.Entry<Integer, String> entry = i.next();
int k = entry.getKey();
String v = entry.getValue();
System.out.println("Key: " + k + " value: " + v);
}
}
}
Output
Key: 1 value: Python Key: 2 value: Java Key: 3 value: C++ Key: 4 value: Js
Creating SortedMap Objects
Since SortedMap is an interface, we cannot directly crate object of this type. we need to use a class that implements this interface such as TreeMap or ConcurrentSkipListMap for a thread-safe version.
With the introduction of Generics in Java 1.5 we can now define the type of object that will be stored in the SortedMap, making it type-safe. This means we can restrict the types of keys and values to specific classes.
Here how we can define and create a type-safe SortedMap:
// Obj1 represents the type of keys
// Obj2 represents the type of values
SortedMap<Obj1, Obj2> map = new TreeMap<Obj1, Obj2>();
Performing Various Operations on SortedMap Interface
1. Adding Elements: We can use the put() method to insert element in an SortedMap.
Example: This example, demonstrates how to insert elements into a SortedMap, where the elements are automatically sorted by their keys.
// Java program to insert elements into a SortedMap
import java.io.*;
import java.util.*;
class Geeks {
public static void main(String args[]) {
// SortedMap with type parameters
// for better type safety
SortedMap<Integer, String> s1 = new TreeMap<>();
SortedMap<Integer, String> s2 = new TreeMap<>();
// Inserting the elements
s1.put(3, "Geeks");
s1.put(2, "For");
s1.put(1, "Geeks");
s2.put(3, "Geeks");
s2.put(2, "For");
s2.put(1, "Geeks");
System.out.println(s1);
System.out.println(s2);
}
}
Output
{1=Geeks, 2=For, 3=Geeks} {1=Geeks, 2=For, 3=Geeks}
2. Changing Elements: To change the element in a SortedMap, we can use the put() method again with the same key but a new value. Since the map stores elements using keys, updating the value is as simple as adding the key with its new value
Example: This example, demonstrates how to update a value in a SortedMap by reinserting the same key with a new value.
// Java program to update a value in a SortedMap
import java.io.*;
import java.util.*;
class Geeks {
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: We can use the remove() method to remove an element from the SortedMap.
Example: This example demonstrates how to insert and remove elements in a SortedMap, where the elements are automatically sorted by their keys.
// Java program to demonstrates how to remove the
// elements from SortedMap
import java.io.*;
import java.util.*;
class Geeks {
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 Element: 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.
Example: This example demonstrates how to iterate over a SortedMap and print each key-value pair.
// Java program to iterate through SortedMap
import java.util.*;
class Geeks {
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.
Example: This example demonstrates how to create a TreeMap with a custom comparator to sort keys in descending order and perform operations like adding and removing elements.
// Java program to demonstrate the
// creation of SortedMap object using
// the TreeMap class
import java.util.*;
class Geeks {
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");
System.out.println(tm);
// Removing items from TreeMap
// using remove()
tm.remove("Australia");
System.out.println("Map after removing Element: " + tm);
}
}
Output
{South Africa=3, India=1, Australia=2} Map after removing Element: {South Africa=3, India=1}
Methods
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
- 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.
- 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.
- 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
- 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.
- 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.