Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
SortedMap tailMap() method in Java
Next article icon

SortedMap Interface in Java

Last Updated : 19 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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
// 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.

SortedMap-in-Java


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
// 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
// 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
// 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
// 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
// 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
// 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

MethodDescription
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

MethodDescription
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.

Next Article
SortedMap tailMap() method in Java

P

Pratik Agarwal
Improve
Article Tags :
  • Java
  • Java-Collections
  • Java - util package
  • java-map
  • Java-SortedMap
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    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 ma
    10 min read
    SortedMap tailMap() method in Java
    The tailMap() method of SortedMap interface in Java is used to return a view of the portion of this map whose keys are greater than or equal to fromKey. The map returned by this method is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The map returned b
    3 min read
    SortedMap firstKey() method in Java
    The firstKey() method of SortedMap interface in Java is used to return the first or the lowest key currently in this map. Syntax: K firstKey() Where, K is the type of key maintained by this Set. Parameters: This function does not accepts any parameter. Return Value: It returns the first print the lo
    2 min read
    SortedMap lastKey() method in Java
    The lastKey() method of SortedMap interface in Java is used to return the last or the greatest key currently in this map. Syntax: K lastKey() Where, K is the type of key maintained by this Set. Parameters: This function does not accepts any parameter. Return Value: It returns the last or the greates
    2 min read
    SortedMap comparator() method in Java with Examples
    The comparator() method of java.util.SortedMap interface is used to return the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.Syntax: public Comparator comparator() Return Value: This method returns the comparator used to order the keys in th
    2 min read
    SortedMap values() method in Java with Examples
    The values() method of SortedMap interface in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the Map. Syntax: SortedMap.values() Parameters: The method does not accept any parameters. Return Value: The method is used to retur
    2 min read
    SortedMap keySet() method in Java with Examples
    The keySet() method of SortedMap Interface in Java is used to create a set out of the key elements contained in the treemap. It basically returns a set view of the keys or we can create a new set and store the key elements in them in an ascending order. Since the set is backed by the map, any change
    2 min read
    SortedMap entrySet() method in Java with Examples
    The entrySet() method of SortedMap interface in Java 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 creates a new set and store the map elements into them. Syntax: SortedMap.entrySet() Parameters: The method does not take any para
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences