Java SortedMap Interface

SortedMap is an interface which is available in java.util package which provides provides sorting of keys stored in a map.

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.

How to use SortedMap:
                        
                            SortedMap<Key, Value> numbers = new TreeMap<>();
                        
                    
Methods of SortedMap
Method Name Description
comparator() returns a comparator that can be used to order keys in a map.
firstKey() returns the first key of the sorted map.
lastKey() returns the last key of the sorted map.
headMap(key) returns all the entries of a map whose keys are less than the specified key.
tailMap(key) returns all the entries of a map whose keys are greater than or equal to the specified key.
subMap(key1, key2) returns all the entries of a map whose keys lies in between key1 and key2 including key1.
Implementation of SortedMap in TreeMap Class
                        
                            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);
                                }
                            }