C

Core Java tutorial for beginners

Clean • Professional

Immutable Collections in Java 9+ – Factory Methods, Benefits & Examples

3 minute

Immutable Collections in Java 9+

Immutable collections are collections that cannot be modified after creation. Once you create them, you cannot add, remove, or change elements.

Java 9 introduced new convenient factory methods to create immutable List, Set, and Map objects easily and safely.


What Are Immutable Collections?

An immutable collection is a collection whose elements cannot be added, removed, or updated once it is created.

  • Useful for read-only data
  • Thread-safe without external synchronization
  • Prevents accidental modifications

Why Immutable Collections?

Immutable collections are useful because they:

learn code with durgesh images

  1. Ensure Thread Safety – Safe for concurrent use without synchronization.
  2. Avoid Bugs – Prevent accidental modifications of data.
  3. Improve Readability – Code clearly shows that collection is unmodifiable.
  4. Optimize Performance – Some implementations can be more memory-efficient.

Immutable Collections in Java 9+

Java 9 introduced factory methods in List, Set, and Map interfaces to create immutable collections:

learn code with durgesh images

  • List.of(...)
  • Set.of(...)
  • Map.of(...)

1. Immutable List

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("A", "B", "C");

        System.out.println(list); // [A, B, C]

        // list.add("D"); //  Throws UnsupportedOperationException
        // list.remove("A"); //  Throws UnsupportedOperationException
    }
}

Key Points:

  • Fixed size
  • Thread-safe
  • Cannot contain null elements (throws NullPointerException)

2. Immutable Set

import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<String> set = Set.of("X", "Y", "Z");

        System.out.println(set); // [X, Y, Z]

        // set.add("A"); //  UnsupportedOperationException
    }
}

Key Points:

  • Unique elements only
  • Cannot contain null
  • Thread-safe

3. Immutable Map

import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<Integer, String> map = Map.of(1, "One", 2, "Two", 3, "Three");

        System.out.println(map); // {1=One, 2=Two, 3=Three}

        // map.put(4, "Four"); //  UnsupportedOperationException
    }
}

Key Points:

  • Key-value pairs
  • Fixed size
  • Thread-safe
  • null keys or values are not allowed

For more than 10 entries, use:

Map<Integer, String> map = Map.ofEntries(
    Map.entry(1, "One"),
    Map.entry(2, "Two"),
    Map.entry(3, "Three")
);

Multi-Element Maps (Java 9+)

For maps with more than 10 entries, use Map.ofEntries():

Map<String, Integer> scores = Map.ofEntries(
    Map.entry("Alice", 90),
    Map.entry("Bob", 85),
    Map.entry("Charlie", 92)
);

Advantages of Immutable Collections

  1. Safe in multi-threaded environments
  2. No defensive copies needed
  3. Simplifies code – prevents accidental modification
  4. Can be used as constant data structures

Limitations

  1. Cannot add, remove, or modify elements
  2. Does not allow null elements
  3. Not suitable if you need dynamic collections

Key Differences Between Java 8 and Java 9+ Immutable Collections

FeatureJava 8Java 9+
CreationCollections.unmodifiableList(...)List.of(...)
NullsAllows nullsNullPointerException for null elements
ConcisenessVerboseConcise & readable
PerformanceExtra wrapper objectOptimized built-in immutable objects

Using Collections.unmodifiable*() vs List.of()

Java 8

List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");

List<String> unmodifiableFruits = Collections.unmodifiableList(fruits);
  • Still wraps a modifiable list; changes in original list affect the unmodifiable view.

Java 9+

List<String> fruits = List.of("Apple", "Banana");
// Truly immutable and concise

Real-World Use Cases

  • Configuration settings: Never-modified values
  • Thread-safe caches: Multiple threads can safely read
  • Constant collections: Lists, maps, and sets used throughout the application
  • Functional programming: Pass collections without worrying about modification

Best Practices

  • Prefer immutable collections when you don’t need modification
  • Use factory methods (List.of, Set.of, Map.of) instead of Collections.unmodifiableList
  • Combine with var keyword for cleaner syntax in Java 10+

Points to Remember

Immutable Collections (Java 9+):

  • Cannot be modified after creation
  • Thread-safe and memory-efficient
  • Created easily using List.of, Set.of, Map.of
  • Prevent accidental bugs and simplify code

Article 0 of 0