Java Collections Framework - The SortedMap Interface

In this guide, we will learn about SortedMap interface, SortedMap interface methods and SortedMap interface implementation class.

Overview of SortedMap Interface

SortedMap is a Map that maintains its entries in ascending order, sorted according to the keys natural ordering, or according to a Comparator provided at the time of the SortedMap creation.
The SortedMap interface provides operations for normal Map operations and for the following:
  • Range view — performs arbitrary range operations on the sorted map
  • Endpoints — returns the first or the last key in the sorted map
  • Comparator access — returns the Comparator, if any, used to sort the map
The following interface is the Map analog of SortedSet.
public interface SortedMap<K, V> extends Map<K, V>{
    Comparator<? super K> comparator();
    SortedMap<K, V> subMap(K fromKey, K toKey);
    SortedMap<K, V> headMap(K toKey);
    SortedMap<K, V> tailMap(K fromKey);
    K firstKey();
    K lastKey();
}

SortedMap Interface with It's TreeSet Implementation Class Example

This example demonstrates the few API of SortedMap Interface using TreeSet implementation class.
  • firstKey()
  • lastKey()
  • tailMap(String fromKey)
  • .headMap(String toKey)
import java.util.SortedMap;

import java.util.TreeMap;

public class CreateTreeMapExample {
    public static void main(String[] args) {
        // Creating a TreeMap
     SortedMap<String, String> fileExtensions  = new TreeMap<>();

        // Adding new key-value pairs to a TreeMap
        fileExtensions.put("python", ".py");
        fileExtensions.put("c++", ".cpp");
        fileExtensions.put("kotlin", ".kt");
        fileExtensions.put("golang", ".go");
        fileExtensions.put("java", ".java");

        // Printing the TreeMap (Output will be sorted based on keys)
        System.out.println(fileExtensions);
        
        System.out.println("First Kay :" + fileExtensions.firstKey());
        
        System.out.println("Last Kay :" + fileExtensions.lastKey());
        
        SortedMap<String, String> sortedMap = fileExtensions.tailMap("java");
        System.out.println("tailMap : " + sortedMap);
        
        sortedMap = fileExtensions.headMap("java");
        System.out.println("headMap : " + sortedMap);
    }
}
Output:
{c++=.cpp, golang=.go, java=.java, kotlin=.kt, python=.py}
First Kay :c++
Last Kay :python
tailMap : {java=.java, kotlin=.kt, python=.py}
headMap : {c++=.cpp, golang=.go}

SortedMap Interface Hierarchy Diagram

SortedMap Interface APIs/Methods

SortedMap Interface Implementations

Comments