Java Utility Library

Java Collections - emptySortedMap() Method



The java.util.Collections.emptySortedMap() method returns an empty sorted map (immutable). This map is serializable.

Syntax

public static final <K,V> SortedMap<K,V> emptySortedMap()

Here, K and V are the type of keys and values, if there were any, in the map.


Parameters

No parameter is required.

Return Value

Returns an empty sorted map.

Exception

NA.

Example:

In the example below, the java.util.Collections.emptySortedMap() method is used to create an empty sorted map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an empty SortedMap
    SortedMap<String, Integer> MyMap = Collections.emptySortedMap();

    //print the content of the map
    System.out.println("MyMap contains: " + MyMap);

    //populating the map
    //as the map is immutable, 
    //the exception is thrown 
    MyMap.put("RED", 1);
    MyMap.put("BLUE", 2);
    MyMap.put("GREEN", 3);

    //print the content of the map
    System.out.println("MyMap contains: " + MyMap);
  }
}

The output of the above code will be:

MyMap contains: {}

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
    at MyClass.main(MyClass.java:14)

❮ Java.util - Collections