Sunday, November 23, 2025
HomeLanguagesJavaJava Collections emptySortedMap() Method with Examples

Java Collections emptySortedMap() Method with Examples

The emptySortedMap() method of Java Collections is used to get a map that has no elements. A Sorted map is a data structure that can hold elements with key-value pairs in sorted order.

Syntax:

public static final <Key,Value> SortedMap<Key,Value> emptySortedMap()  

where,

  • key is the key element
  • value is the value element

Parameters: This method does not take any parameters.

Return Type: It will return an empty sorted map that is immutable.

Example 1:

Java program to create an empty sorted map.

Java




import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // create an empty sorted map
        SortedMap<String, String> data
            = Collections.emptySortedMap();
  
        // display
        System.out.println(data);
    }
}


Output

{}

Example 2:

In this program, we are going to create an empty sorted map and add elements to the map. This method will return an error.

Java




import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // create an empty sorted map
        SortedMap<String, String> data
            = Collections.emptySortedMap();
        
        // add 3 elements
        data.put("1", "ojaswi");
        data.put("2", "ramya");
        data.put("3", "deepu");
  
        // display
        System.out.println(data);
    }
}


Output:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableMap.put(Collections.java:1459)
    at GFG.main(GFG.java:10)

Example 3:

Java




import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // create an empty sorted map
        SortedMap<Integer, Integer> data
            = Collections.emptySortedMap();
        
        // add 3 elements
        data.put(1, 34);
        data.put(2, 45);
        data.put(3, 56);
  
        // display
        System.out.println(data);
    }
}


Output:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableMap.put(Collections.java:1459)
    at GFG.main(GFG.java:10)
RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS