Java Programming Tutorials

Java programming tutorials with many code examples!

Java singleton List


How to create Java singleton List is the easiest way? Java Collections Framework has a couple of handy methods to create singleton List, singleton Set, and singleton Map. See the example.


In java.util.Collections there are the following helper methods:

  • <T> Set<T> singleton(T o): creates an immutable Set with given element
  • <T> List<T> singletonList(T o): creates an immutable List with given element
  • <K,V> Map<K,V> singletonMap(K key, V value): creates an immutable Map with only the given pair.

In the following example Java program you can see that the created collection is really immutable and trying to do any modification results in UnsupportedOperationException:


import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class CollectionsSingleton {

    public static void main(String[] args) {



    private static void showImmutability() {
        List<Integer> singleton = Collections.singletonList(42);

        System.out.println("singleton List: " + singleton);

        try {
        } catch (UnsupportedOperationException e) {
            System.out.println("While adding: " + e);

        try {
        } catch (UnsupportedOperationException e) {
            System.out.println("While removing: " + e);

        try {
            singleton.set(0, 3);
        } catch (UnsupportedOperationException e) {
            System.out.println("While setting: " + e);

    private static void showUseCase() {
        List<String> scores = new LinkedList<>(Arrays.asList("1", "2", "3", "1", "4"));
        System.out.println("Scores: " + scores);
        System.out.println("After scores.remove(1): " + scores);

        scores = new LinkedList<>(Arrays.asList("1", "2", "3", "1", "4"));
        System.out.println("Scores: " + scores);
        System.out.println("After scores.removeAll(singleton(1)): " + scores);

In the method showUseCase() you can see how Collections.singleton(T o) is used to create an one-element collection to remove all occurrences of an object in the List.

Note that in the example we have to wrap List created by Arrays.asList() into another List, because the former one doesn’t support remove() operation, so we wouldn’t be able to remove anything.

And here’s the result of running the Java program:

singleton List: [42]
While adding: java.lang.UnsupportedOperationException
While removing: java.lang.UnsupportedOperationException
While setting: java.lang.UnsupportedOperationException

Scores: [1, 2, 3, 1, 4]
After scores.remove(1): [2, 3, 1, 4]
Scores: [1, 2, 3, 1, 4]
After scores.removeAll(singleton(1)): [2, 3, 4]

As an alternative to singleton methods from java.util.Collections you can use unmodifiable series of methods from java.util.Collections or ImmutableSet, ImmutableList, and ImmutableMap from great Guava library.

Was it helpful? Share!