The emptySortedMap()
method in Java returns an immutable SortedMap
that contains no key-value pairs. It is part of the java.util.Collections
class and provides a convenient way to obtain an empty sorted map, which can be useful in scenarios where a method requires a sorted map but no mappings are available.
Table of Contents
- Introduction
emptySortedMap()
Method Syntax- Examples
- Basic Usage of
emptySortedMap()
- Using
emptySortedMap()
in a Custom Method
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.emptySortedMap()
method returns a statically typed, immutable sorted map that contains no elements. This method is useful when you need to return a sorted map from a method, but there are no key-value pairs to provide. By using emptySortedMap()
, you can avoid returning null
and prevent potential NullPointerException
errors in your code.
A SortedMap
is an interface that extends the Map
interface and provides additional methods for dealing with ordered key-value pairs. The map returned by emptySortedMap()
is immutable, meaning it cannot be modified. Any attempts to add, remove, or change entries will result in an UnsupportedOperationException
.
emptySortedMap() Method Syntax
The syntax for the emptySortedMap()
method is as follows:
public static final <K, V> SortedMap<K, V> emptySortedMap()
Parameters:
- This method does not take any parameters.
Returns:
- An immutable empty
SortedMap
.
Examples
Basic Usage of emptySortedMap()
The following example demonstrates how to use the emptySortedMap()
method to obtain an immutable empty sorted map.
Example
import java.util.Collections;
import java.util.SortedMap;
public class EmptySortedMapExample {
public static void main(String[] args) {
// Obtain an empty sorted map
SortedMap<String, Integer> emptySortedMap = Collections.emptySortedMap();
// Check if the sorted map is empty
System.out.println("Is the sorted map empty? " + emptySortedMap.isEmpty());
// Attempt to access entries in the sorted map
System.out.println("Sorted map size: " + emptySortedMap.size());
// Attempt to modify the sorted map (will throw UnsupportedOperationException)
try {
emptySortedMap.put("Key", 1);
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot add entries to an immutable sorted map");
}
}
}
Output:
Is the sorted map empty? true
Sorted map size: 0
Error: Cannot add entries to an immutable sorted map
Using emptySortedMap() in a Custom Method
You can use the emptySortedMap()
method to return an empty sorted map from a custom method when there are no key-value pairs to provide.
Example
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
public class CustomMethodExample {
public static void main(String[] args) {
// Get a non-empty sorted map of students and their scores
SortedMap<String, Integer> studentScores = getStudentScores(true);
System.out.println("Student Scores (non-empty): " + studentScores);
// Get an empty sorted map of students and their scores
studentScores = getStudentScores(false);
System.out.println("Student Scores (empty): " + studentScores);
}
// Method to return a sorted map of students and their scores based on a condition
public static SortedMap<String, Integer> getStudentScores(boolean hasScores) {
if (hasScores) {
SortedMap<String, Integer> scores = new TreeMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
return scores;
} else {
return Collections.emptySortedMap();
}
}
}
Output:
Student Scores (non-empty): {Alice=90, Bob=85}
Student Scores (empty): {}
Explanation:
-
Non-Empty Sorted Map: When
hasScores
istrue
, thegetStudentScores()
method returns a sorted map containing student names and their scores using aTreeMap
. -
Empty Sorted Map: When
hasScores
isfalse
, the method returns an empty sorted map usingemptySortedMap()
, demonstrating its utility in cases where no entries are needed.
Real-World Use Case
Providing Default Empty Sorted Maps in APIs
In API development, it is common to have methods that return sorted maps. Using emptySortedMap()
can provide a safe default when there are no key-value pairs to return, avoiding null values and potential errors.
Example
Imagine a scenario where you have an API method that retrieves a sorted map of employee IDs and their associated salaries based on specific criteria. If no employees meet the criteria, you can return an empty sorted map instead of null
.
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
class Employee {
String name;
int salary;
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
@Override
public String toString() {
return name + " ($" + salary + ")";
}
}
public class EmployeeService {
// Method to get a sorted map of employee names and their salaries based on a condition
public SortedMap<String, Integer> getEmployeeSalaries(boolean hasEmployees) {
if (hasEmployees) {
SortedMap<String, Integer> employeeSalaries = new TreeMap<>();
employeeSalaries.put("John", 70000);
employeeSalaries.put("Jane", 80000);
return employeeSalaries;
} else {
return Collections.emptySortedMap();
}
}
public static void main(String[] args) {
EmployeeService employeeService = new EmployeeService();
// Retrieve a non-empty sorted map of employee salaries
SortedMap<String, Integer> employeeSalaries = employeeService.getEmployeeSalaries(true);
System.out.println("Employee Salaries (non-empty): " + employeeSalaries);
// Retrieve an empty sorted map of employee salaries
employeeSalaries = employeeService.getEmployeeSalaries(false);
System.out.println("Employee Salaries (empty): " + employeeSalaries);
}
}
Output:
Employee Salaries (non-empty): {Jane=80000, John=70000}
Employee Salaries (empty): {}
Explanation:
-
Non-Empty Sorted Map: When
hasEmployees
istrue
, thegetEmployeeSalaries()
method returns a sorted map of employee salaries, demonstrating how maps can be populated with entries when available. -
Empty Sorted Map: When
hasEmployees
isfalse
, thegetEmployeeSalaries()
method returns an empty sorted map usingemptySortedMap()
, ensuring that the method handles cases with no employees correctly.
Conclusion
The Collections.emptySortedMap()
method is a useful utility for obtaining an immutable empty sorted map in Java. By providing a typesafe, empty sorted map, it helps prevent NullPointerException
errors and ensures that your code handles cases where no elements are present gracefully. This method is particularly valuable when implementing APIs or methods that require sorted maps but may not always have entries to return, enhancing the robustness and maintainability of your Java applications.