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.


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("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);
{c++=.cpp, golang=.go,, kotlin=.kt,}
First Kay :c++
Last Kay :python
tailMap : {, kotlin=.kt,}
headMap : {c++=.cpp, golang=.go}


Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course