Java Collections emptySortedMap() Method with Examples
Last Updated :
03 Jan, 2022
Improve
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.
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.
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:
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)