SortedMap Interface in Java with Example | Java SortedMap Implementation in TreeMap Class | Constructors & Methods of Java Sorted Map

SortedMap is an interface in the collection framework. The Java SortedMap interface, java.util.SortedMap, is a subtype of the java.util.Map interface. In this tutorial, beginners and experienced program passionate can learn easily about the Java SortedMap interface and its methods with examples. Hence, go with the direct links available here and study various java map interfaces in detail.

This SortedMap Interface in Java Tutorial Comprises: 

Java SortedMap Interface

SortedMap is the child interface of Map. If we want to represent a group of key/values pairs according to some sorting order of keys then we should go for SortedMap in Java. Sorting is based on the keys but not value. Sorted maps allow very efficient manipulations of submaps(subsets of a map). To obtain a subset of a map we can use headMap(), tailMap(), or subMap(). To get the first key and the last key we can use firstKey(), lastKey() respectively.

A NoSuchElementexception is thrown when no items are in the invoking map, A ClassCastException is thrown when an object is incompatible with the elements in the map i.e. if we use heterogeneous keys, A NullPointerException is thrown when we insert a null element in the map, A IllegalArgumentException is thrown if invalid arguments we used.

Hierarchy of SortedMap Interface in Java

SortedMap Interface in Java with Example 1

Do Check:

Class that implements SortedMap

We can’t create objects from the SortedMap as it an interface. To utilize the functionalities of a SortedMap, we have to use the TreeMap class that implements a sorted map.

java sortedmap with treemap image

How to Use SortedMap?

In order to utilize the SortedMap, we need to import the java.util.SortedMap package. Once we have done with the package import, here’s how we can create a sorted map in java.

// SortedMap implementation by TreeMap class
SortedMap<Key, Value> digits= new TreeMap<>();

We have built a sorted map called digits using the TreeMap class.

Here,

Key – a unique identifier used to connect each element (value) in a map
Value – elements connected by keys in a map

Above, we have taken no arguments to create a sorted map. So, the map will be sorted naturally (ascending order).

Creating SortedMap Objects

As it is an interface, no object can be created of the type SortedMap. To create an object, we must have a class that extends this list. However, after the introduction of Generics in Java 1.5, there is a possibility to restrict the type of object that can be saved in the SortedMap. Here, is the definition of this type-safe map.

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

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

Java SortedMap Constructors

According to the specification, all general-purpose class implementations of the sorted map need to provide the following standard constructors:

  • A void (no arguments) constructor: It creates a sorted map that is sorted as per the natural ordering of its keys.
  • A constructor with an argument of type Comparator: It must create a sorted map whose keys are sorted according to the defined comparator.
  • A constructor with an argument of type Map: It needs to create a sorted map with elements of the given map which is sorted according to the natural ordering of its keys.
  • A constructor with an argument of type SortedMap: It should work as a copy constructor and build a new sorted map with the same elements and the same ordering of provided sorted map.

Certainly, it’s difficult to implement this recommendation, as interfaces can’t specify the constructors unlike methods.

Java SortedMap Implementation in TreeMap Class

In java, you can observe easy built-in implementations like SortedMap. TreeMap(java.util.TreeMap) and ConcurrentSkipListMap classes implements the SortedMap interface.

Create a TreeMap

There is a possibility to create a treemap instance through the constructor. Below, we have provided an example syntax of the Java TreeMap instance, which implements the SortedMap interface:

SortedMap sortedMap = new TreeMap();

Create a TreeMap With Comparator

By taking help from the below syntax, you can easily understand how to create a TreeMap with Comparator.

Comparator comparator = new MyComparatorImpl();

SortedMap sortedMap = new TreeMap(comparator);

Implementation of SortedMap in TreeMap Class Example

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

class Main {

public static void main(String[] args) {
// Creating SortedMap using TreeMap
SortedMap<String, Integer> numbers = new TreeMap<>();

// Insert elements to map
numbers.put("Two", 2);
numbers.put("One", 1);
System.out.println("SortedMap: " + numbers);

// Access the first key of the map
System.out.println("First Key: " + numbers.firstKey());

// Access the last key of the map
System.out.println("Last Key: " + numbers.lastKey());

// Remove elements from the map
int value = numbers.remove("One");
System.out.println("Removed Value: " + value);
}
}

Output:

SortedMap: {One=1, Two=2}
First Key: One
Last Key: Two
Removed Value: 1

Methods of SortedMap in Java

The SortedMap defines the following specific methods.

  • Object firstKey(): This method is used to returns the first key in the invoking map.
  • Object lastKey(): This method is used to returns the last key in the invoking map.
  • SortedMap subMap(Object start, Object end): This method returns a map containing those entries with keys that are greater than or equal to start and less than the end.
  • SortedMap headMap(Object end): This method returns a sorted map for those entries with keys that are less than the end.
  • SortedMap tailMap(Object start): This method returns a sorted map whose entries with keys are greater than or equal to start.
  • Comparator comparator(): This method returns the invoking sorted map comparator. It returns null if the natural ordering is used for the invoking map.

Java SortedMap Example

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

class SortedMapExample{
public static void main(String args[]){

//creating a sorted map
SortedMap<Integer, String> smap = new TreeMap<Integer, String>();

//adding values in this map
smap.put(101, "Rahul");
smap.put(107, "Amit");
smap.put(103, "Vijay");
smap.put(105, "Suresh");
smap.put(102, "John");
smap.put(106, "Prashant");

System.out.println(" Sorted Map entries are: "+smap);

//returns first key in the invoking map
System.out.println("Map first key is: "+smap.firstKey());

//returns last key in the invoking map
System.out.println("Map last key is: "+smap.lastKey());

/*returns a sorted map for those entries with keys that are less than the end.*/
System.out.println("Head map is: "+smap.headMap(103));

/*returns a sorted map whose entries with keys that are greater than or equal to the specified key.*/
System.out.println("Tail map is: "+smap.tailMap(102));

//It returns subset of a map
System.out.println("Sub map is: "+smap.subMap(103,106));

}
}

Output

SortedMap Interface in Java with Example 2

Leave a Comment