The singletonList() method in Java is a utility method provided by the java.util.Collections class. It returns an immutable list containing only a specified object. This method is useful when you need to create a list with exactly one element, providing a convenient and efficient way to represent single-element lists in your application.
Table of Contents
- Introduction
singletonList()Method Syntax- Examples
- Basic Usage of
singletonList() - Using
singletonList()with Custom Classes
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.singletonList() method is designed to create a list that contains exactly one element. The returned list is immutable, meaning it cannot be modified after creation. This is useful in scenarios where you need to pass a single element as a list or when you need to enforce a single-element collection in your logic.
The singleton list ensures that the specified element is the only one present, and any attempt to modify the list will result in an UnsupportedOperationException.
singletonList() Method Syntax
The syntax for the singletonList() method is as follows:
public static <T> List<T> singletonList(T o)
Parameters:
o: The single element to be stored in the returned list.
Returns:
- An immutable list containing only the specified object.
Throws:
NullPointerExceptionif the specified object is null.
Examples
Basic Usage of singletonList()
The following example demonstrates how to use the singletonList() method to create a list containing a single string.
Example
import java.util.Collections;
import java.util.List;
public class SingletonListExample {
public static void main(String[] args) {
// Create a singleton list containing a single element "Hello"
List<String> singletonList = Collections.singletonList("Hello");
// Display the singleton list
System.out.println("Singleton List: " + singletonList);
// Attempt to modify the singleton list (will throw UnsupportedOperationException)
try {
singletonList.add("World");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an immutable singleton list");
}
}
}
Output:
Singleton List: [Hello]
Error: Cannot modify an immutable singleton list
Using singletonList() with Custom Classes
You can also use the singletonList() method to create a list containing a single instance of a custom class.
Example
import java.util.Collections;
import java.util.List;
class Student {
String name;
Student(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class CustomSingletonListExample {
public static void main(String[] args) {
// Create a Student object
Student student = new Student("Amit");
// Create a singleton list containing the Student object
List<Student> singletonStudentList = Collections.singletonList(student);
// Display the singleton student list
System.out.println("Singleton Student List: " + singletonStudentList);
// Attempt to modify the singleton student list (will throw UnsupportedOperationException)
try {
singletonStudentList.add(new Student("Neha"));
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an immutable singleton student list");
}
}
}
Output:
Singleton Student List: [Amit]
Error: Cannot modify an immutable singleton student list
Explanation:
-
Single Element: The
singletonList()method creates a list containing only the specified single element, ensuring immutability. -
Immutable Nature: Any attempt to modify the singleton list results in an
UnsupportedOperationException, demonstrating the immutability of the list. -
Custom Class: The method works with custom class instances, allowing you to create single-element lists with user-defined objects.
Real-World Use Case
Returning a Single Element List from a Method
In real-world applications, the singletonList() method can be used to return a single-element list from a method, simplifying code that requires a list but only needs to handle one element.
Example
Imagine a scenario where you need to return a list of permissions for a user, and the user has only one specific permission.
import java.util.Collections;
import java.util.List;
class Permission {
String name;
Permission(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class PermissionExample {
public static void main(String[] args) {
// Get a list of permissions for a user
List<Permission> userPermissions = getUserPermissions("admin");
// Display the user's permissions
System.out.println("User Permissions: " + userPermissions);
}
// Method to return a singleton list of permissions based on user role
public static List<Permission> getUserPermissions(String role) {
if ("admin".equals(role)) {
return Collections.singletonList(new Permission("FULL_ACCESS"));
} else {
return Collections.singletonList(new Permission("READ_ONLY"));
}
}
}
Output:
User Permissions: [FULL_ACCESS]
Explanation:
-
Permission Logic: The
getUserPermissions()method returns a singleton list based on the user’s role, ensuring that each role has a specific, immutable permission list. -
Single Element List: The singleton list simplifies the handling of permissions by enforcing a single-element collection, reducing complexity and improving code clarity.
Conclusion
The Collections.singletonList() method is a powerful utility for creating immutable lists containing a single element in Java. By providing a simple way to represent single-element collections, it enhances the flexibility and readability of your code. This method is particularly valuable in scenarios where you need to enforce single-element collections, improving the robustness and maintainability of your Java applications.