The SortedMap
interface of the Java collections framework provides sorting of keys stored in a map.
It extends the Map interface.
Since SortedMap
is an interface, we cannot create objects from it.
In order to use the functionalities of the SortedMap
interface, we need to use the class TreeMap
that implements it.
To use the SortedMap
, we must import the java.util.SortedMap
package first. Once we import the package, here's how we can create a sorted map.
// SortedMap implementation by TreeMap class
SortedMap<Key, Value> numbers = new TreeMap<>();
We have created a sorted map called numbers using the TreeMap
class.
Here,
Here, we have used no arguments to create a sorted map. Hence the map will be sorted naturally (ascending order).
The SortedMap
interface includes all the methods of the Map
interface. It is because Map
is a super interface of SortedMap
.
Besides all those methods, here are the methods specific to the SortedMap
interface.
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
Here, we show how the SortedMap
interface works.