SortedMap in Java | Methods, Example

Last Updated on December 19, 2020 by Scientech Easy

SortedMap in Java is an interface that is a subinterface of Map interface. The entries in the map are maintained in sorted ascending order based on their keys.

In simple words, it guarantees that the entries are maintained in ascending key order. It allows very efficient manipulations of subsets of a map.

SortedMap was added in Java 1.2 version. It is present in java.util.SortedMap package.

Hierarchy of SortedMap Interface in Java


SortedMap interface extends Map interface. TreeMap and ConcurrentSkipListMap classes implements the SortedMap interface. The hierarchy diagram of SortedMap interface in java is shown below in the figure.Java SortedMap hierarchy diagram

SortedMap Interface


SortedMap is a generic interface that is declared as shown below:

interface SortedMap<K,V>
     extends Map<K,V>

Here, K represents the type of keys maintained by this map and V represents the type of mapped values.

SortedMap Methods in Java


In addition to the methods provided by Map interface, SortedMap also provides several additional methods that are as follows:

1. Comparator comparator(): This method returns the comparator used to order the keys in this map. If the map uses the natural ordering of its keys, null is returned.

2. Set<Map.Entry<K,V>> entrySet(): This method returns a set view of the key-value pairs (mappings) contained in this map.

3. Set<K> keySet(): It returns a set view of the keys contained in this map.

4. K firstKey(): It returns the first (lowest or smallest) key in the invoking map.

5. K lastKey(): It returns the last (highest or largest) key in the invoking map.

6. SortedMap<K,V> headMap(K toKey): This method returns a portion of the map whose keys are strictly less than toKey.

7. SortedMap<K,V> tailMap(K fromKey): This method returns a portion of the map whose keys are greater than or equal to fromKey.


8. SortedMap<K,V> subMap(K fromKey, K toKey): This method returns a portion of the map whose keys range from fromKey, inclusive, to toKey, exclusive.

Methods inherited from Map interface

clear(), containsKey(), containsValue(), equals(), get(), hashCode(), isEmpty(), put(), putAll(), remove(), size()

Several methods throw an exception named NoSuchElementException if no entries are in the invoking map. When an object is not compatible with elements in the map, ClassCastException is thrown.

If you attempt to use a null object when null is not allowed in the map, a runtime exception named NullPointerException will be thrown.

Java SortedMap Example Programs


Let’s take example programs for performing the various operations based on the methods defined by SortedMap interface in Java.

Since Java SortedMap is an interface, it can be used only with class that implements SortedMap interface. TreeMap class in Java implements the SortedMap interface.

1. Adding and Removing Elements: Let’s create a program where we will add and remove an element to the SortedMap using the put() and remove() methods respectively. However, the insertion order is not preserved in the TreeMap.

Internally, for every element, the keys are compared and sorted according to ascending order. Look at the following source code to understand better.

Program source code 1:

import java.util.SortedMap;
import java.util.TreeMap;

public class SortedMapEx {	
public static void main(String[] args)
{	
// Create a SortedMap.
  SortedMap<Integer, String> smap = new TreeMap<>();
  
// Adding entries in TreeMap.
   smap.put(10, "Ten");
   smap.put(20, "Twenty");
   smap.put(05, "Five");
   smap.put(07, "Seven");
   smap.put(40, "Forty");
   
System.out.println("Entries in map: " +smap);
  
// Removing an entry.
   Object removeEntry = smap.remove(05);
   System.out.println("Removed entry: " +removeEntry);
   System.out.println("Updated entries in map after remove operation: " +smap);
   
 }
}
Output:
      Entries in map: {5=Five, 7=Seven, 10=Ten, 20=Twenty, 40=Forty}
      Removed entry: Five
      Updated entries in map after remove operation: {7=Seven, 10=Ten, 20=Twenty, 40=Forty}

2. Updating entries: After adding entries if you want to update an entry, it can be done by again adding an entry with the put() method.

Since entries in the SortedMap are indexed using keys, the value of the key can be updated or changed by simply inserting the updated value for the key for which you wish to change.

Program source code 2:

import java.util.SortedMap;
import java.util.TreeMap;

public class SortedMapEx2 {	
public static void main(String[] args)
{	
// Create a SortedMap.
  SortedMap<Integer, String> smap = new TreeMap<>();
  
   smap.put(06, "Six");
   smap.put(20, "Twenty");
   smap.put(05, "Fie"); // Here, an entry is wrong.
   smap.put(07, "Seven");
   smap.put(40, "Forty");
   
System.out.println("Entries in map: " +smap.entrySet());
  
// Updating the spelling of wrong entry.
   smap.put(05, "Five");
   System.out.println("Updated entries in map: " +smap.entrySet());
   System.out.println("SubMap: " +smap.subMap(10, 45));
 }
}
Output:
      Entries in map: [5=Fie, 6=Six, 7=Seven, 20=Twenty, 40=Forty]
      Updated entries in map: [5=Five, 6=Six, 7=Seven, 20=Twenty, 40=Forty]
      SubMap: {20=Twenty, 40=Forty}

3. Let’s take another example program to perform various operations based on headMap(), tailMap(), firstKey(), and lastKey() methods. Look at the following source code to understand better.

Program source code 3:

import java.util.SortedMap;
import java.util.TreeMap;

public class SortedMapEx3 {	
public static void main(String[] args)
{	
// Create a SortedMap.
  SortedMap<Integer, String> smap = new TreeMap<Integer,String>();
  
// Adding entries in TreeMap.
   smap.put(90, "John");
   smap.put(85, "Deep");
   smap.put(100, "Sophia");
   smap.put(35, "Olivea");
   smap.put(39, "Shubh");
   
System.out.println("Marks in maths: " +smap); 
System.out.println("Students that passed maths exam: " +smap.tailMap(40));
System.out.println("Students that failed in maths exam: " +smap.headMap(40));

System.out.println("Lowest marks: " +smap.firstKey());
System.out.println("Highest marks: " +smap.lastKey());
 }
}
Output:
      Marks in maths: {35=Olivea, 39=Shubh, 85=Deep, 90=John, 100=Sophia}
      Students that passed maths exam: {85=Deep, 90=John, 100=Sophia}
      Students that failed in maths exam: {35=Olivea, 39=Shubh}
      Lowest marks: 35
      Highest marks: 100

Hope that this tutorial has covered important points related to SortedMap interface in Java with example programs. I hope that you will have understood this topic.
Thanks for reading!!!