In Java, Collections.singletonList(o) returns a List of size 1 whose only element is o. The list is immutable: you cannot add, remove, or even replace that element.
Reach for it when a method wants a List but you only have one value, for example a single email recipient or a default choice. It is lighter than building an ArrayList for one item.
A static method of the java.util.Collections utility class, available since Java 1.3. Call it on the class name, as in Collections.singletonList(...), after import java.util.Collections;. You never create a Collections object.
Syntax
Pass the single element.
Java
List<String> to = Collections.singletonList("[email protected]");
sendAll(to); // a method that takes List<String>
String only = to.get(0); // "[email protected]"
Call
What it does
Collections.singletonList(x)
Immutable list [x].
Arrays.asList(x)
Fixed-size list [x]; set(0, y) is allowed.
new ArrayList<>(Collections.singletonList(x))
Changeable list starting with x.
List.of(x)
Java 9+ immutable list; rejects null.
Added in Java 1.3. The returned list supports fast index access, so get(0) is instant; get(1) or any other index throws IndexOutOfBoundsException.
Library declarations
Java
// java.util.Collections
public static <T> List<T> singletonList(T o)
A mailing method takes a List of addresses. Send to a single person without building an ArrayList.
Java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CollectionsSingletonListMail {
static int send(List<String> recipients) {
for (String r : recipients) {
System.out.println("sending to " + r);
}
return recipients.size();
}
public static void main(String[] args) {
int a = send(Arrays.asList("[email protected]", "[email protected]"));
int b = send(Collections.singletonList("[email protected]"));
System.out.println("sent " + a + " + " + b);
}
}