Java SortedMap Interface Example

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.

Read more at https://www.javaguides.net/2018/08/collections-framework-the-sortedmap-interface.html.

Java SortedMap Interface 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}

Reference

Comments