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

Comparing Factory Methods with Java 9+ Collection Factories

Contrast Collections utility factories with modern List.of, Set.of, and Map.of convenience methods.

Comparing Factory Methods with Java 9+ Collection Factories

You'll learn how traditional Collections utility factories compare to modern Java 9+ convenience methods like List.of(), Set.of(), and Map.of().

Now that you've explored the Collections class utility methods like singleton(), emptyList(), and unmodifiableList(), it's time to see how Java 9+ simplifies immutable collection creation with modern factory methods.

The Old Way: Collections Utility Class

Before Java 9, creating immutable collections required multiple steps:

// Creating an immutable list the old way
List<String> oldList = Collections.unmodifiableList(
    new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry"))
);

// Creating a singleton set
Set<String> oldSingleton = Collections.singleton("Only");

// Empty collections
List<Integer> oldEmpty = Collections.emptyList();

This approach was verbose and required wrapping mutable collections.

The New Way: Java 9+ Factory Methods

Java 9 introduced concise factory methods that create truly immutable collections directly:

// Modern immutable list
List<String> newList = List.of("Apple", "Banana", "Cherry");

// Modern immutable set
Set<String> newSet = Set.of("Red", "Green", "Blue");

// Modern immutable map
Map<String, Integer> newMap = Map.of("One", 1, "Two", 2);

// Empty collections
List<Integer> newEmpty = List.of();

Key Differences

  • Syntax: List.of() is cleaner than Collections.unmodifiableList(new ArrayList<>())
  • True Immutability: Java 9+ factories create truly immutable collections, not just unmodifiable views
  • Null Rejection: List.of() throws NullPointerException on null elements; old methods often allowed nulls
  • Performance: Factory methods are optimized with specialized implementations for small sizes

Key Takeaway: Java 9+ collection factories (List.of, Set.of, Map.of) provide a cleaner, safer, and more efficient way to create immutable collections compared to the traditional Collections utility wrappers.