The singletonMap() method in Java is a utility method provided by the java.util.Collections class. It returns an immutable map containing a single key-value mapping. This method is useful when you need to create a map with exactly one entry, providing a convenient and efficient way to represent simple mappings in your application.
Table of Contents
- Introduction
singletonMap()Method Syntax- Examples
- Basic Usage of
singletonMap() - Using
singletonMap()with Custom Classes
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.singletonMap() method is designed to create a map that contains exactly one key-value pair. The returned map is immutable, meaning that it cannot be modified after creation. This is useful in scenarios where you need to pass a single mapping as a map or when you need to enforce a single-entry collection in your logic.
The singleton map ensures that the specified key-value pair is the only mapping present, and any attempt to modify the map will result in an UnsupportedOperationException.
singletonMap() Method Syntax
The syntax for the singletonMap() method is as follows:
public static <K, V> Map<K, V> singletonMap(K key, V value)
Parameters:
key: The key for the singleton map.value: The value to be associated with the key in the map.
Returns:
- An immutable map containing only the specified key-value mapping.
Throws:
NullPointerExceptionif the specified key or value is null.
Examples
Basic Usage of singletonMap()
The following example demonstrates how to use the singletonMap() method to create a map containing a single key-value pair.
Example
import java.util.Collections;
import java.util.Map;
public class SingletonMapExample {
public static void main(String[] args) {
// Create a singleton map with a single key-value pair
Map<String, String> singletonMap = Collections.singletonMap("key", "value");
// Display the singleton map
System.out.println("Singleton Map: " + singletonMap);
// Attempt to modify the singleton map (will throw UnsupportedOperationException)
try {
singletonMap.put("newKey", "newValue");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an immutable singleton map");
}
}
}
Output:
Singleton Map: {key=value}
Error: Cannot modify an immutable singleton map
Using singletonMap() with Custom Classes
You can also use the singletonMap() method to create a map containing a single mapping of custom class instances.
Example
import java.util.Collections;
import java.util.Map;
class Student {
String name;
Student(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class CustomSingletonMapExample {
public static void main(String[] args) {
// Create a Student object
Student student = new Student("Amit");
// Create a singleton map with a Student object as the key and an Integer as the value
Map<Student, Integer> studentScoreMap = Collections.singletonMap(student, 95);
// Display the singleton student map
System.out.println("Singleton Student Map: " + studentScoreMap);
// Attempt to modify the singleton student map (will throw UnsupportedOperationException)
try {
studentScoreMap.put(new Student("Neha"), 85);
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an immutable singleton student map");
}
}
}
Output:
Singleton Student Map: {Amit=95}
Error: Cannot modify an immutable singleton student map
Explanation:
-
Single Mapping: The
singletonMap()method creates a map containing only the specified single key-value pair, ensuring immutability. -
Immutable Nature: Any attempt to modify the singleton map results in an
UnsupportedOperationException, demonstrating the immutability of the map. -
Custom Class: The method works with custom class instances, allowing you to create single-entry maps with user-defined objects.
Real-World Use Case
Returning a Single Entry Map from a Method
In real-world applications, the singletonMap() method can be used to return a single-entry map from a method, simplifying code that requires a map but only needs to handle one entry.
Example
Imagine a scenario where you need to return a map of configuration settings for a module, and the module has only one specific setting.
import java.util.Collections;
import java.util.Map;
class Configuration {
String settingName;
String settingValue;
Configuration(String settingName, String settingValue) {
this.settingName = settingName;
this.settingValue = settingValue;
}
@Override
public String toString() {
return settingName + "=" + settingValue;
}
}
public class ConfigurationExample {
public static void main(String[] args) {
// Get a map of configuration settings for a module
Map<String, Configuration> configSettings = getModuleConfig("module1");
// Display the module's configuration settings
System.out.println("Module Configuration Settings: " + configSettings);
}
// Method to return a singleton map of configuration settings based on module name
public static Map<String, Configuration> getModuleConfig(String moduleName) {
if ("module1".equals(moduleName)) {
return Collections.singletonMap("timeout", new Configuration("timeout", "30s"));
} else {
return Collections.singletonMap("timeout", new Configuration("timeout", "60s"));
}
}
}
Output:
Module Configuration Settings: {timeout=timeout=30s}
Explanation:
-
Configuration Logic: The
getModuleConfig()method returns a singleton map based on the module name, ensuring that each module has a specific, immutable configuration setting. -
Single Entry Map: The singleton map simplifies the handling of configuration settings by enforcing a single-entry collection, reducing complexity and improving code clarity.
Conclusion
The Collections.singletonMap() method is a powerful utility for creating immutable maps containing a single key-value mapping in Java. By providing a simple way to represent single-entry collections, it enhances the flexibility and readability of your code. This method is particularly valuable in scenarios where you need to enforce single-entry collections, improving the robustness and maintainability of your Java applications.