Course contentsShow
← Java
Lesson 1255 of 2,87028. Collections Utility ClassFree lesson

Collections.singleton, singletonList, and singletonMap

Create immutable collections containing exactly one element using singleton factory methods.

Collections.singleton, singletonList, and singletonMap

What You'll Learn

You'll learn how to create immutable, single-element collections using Java's efficient singleton factory methods.

The Core Idea

Sometimes you need a collection containing exactly one element—perhaps to pass to a method expecting a collection parameter, or to use as a constant. Instead of creating a full collection and making it unmodifiable, Java provides three specialized factory methods: Collections.singleton(), Collections.singletonList(), and Collections.singletonMap().

These methods create immutable collections containing just one element. They're more memory-efficient than regular collections because they don't need to allocate space for multiple elements or manage growth.

The Three Singleton Methods

Collections.singleton(element) - Returns an immutable Set containing one element:

Set<String> oneItem = Collections.singleton("apple");
// oneItem.add("banana"); // throws UnsupportedOperationException

Collections.singletonList(element) - Returns an immutable List containing one element:

List<Integer> oneNumber = Collections.singletonList(42);
System.out.println(oneNumber.get(0)); // prints 42

Collections.singletonMap(key, value) - Returns an immutable Map containing one key-value pair:

Map<String, Integer> oneEntry = Collections.singletonMap("score", 100);
System.out.println(oneEntry.get("score")); // prints 100

Why Use These?

Think of singleton collections as "read-only boxes" containing exactly one item. They're perfect when you need to:

  • Pass a single value to a method expecting a collection
  • Create lightweight constant collections
  • Avoid the overhead of full collection implementations

Unlike List.of() or Set.of(), these methods have been around since Java 1.3, making them useful in legacy codebases.

Key Takeaway: Use Collections.singleton(), singletonList(), and singletonMap() to create memory-efficient, immutable collections containing exactly one element—they're simpler and lighter than creating and wrapping full collections.