Java

Immutable Collections — List.of / Map.of

admin by @admin ADMIN
6d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Java 9+ static factory methods return immutable collections with no nulls allowed. Concise, fast, and safer to share across threads or APIs than mutable equivalents.
Java
Raw
import java.util.*;

class Demo {
    static final List<String> ROLES = List.of("admin", "editor", "viewer");
    static final Set<String>  PERMS = Set.of("read", "write", "delete");
    static final Map<String, Integer> LIMITS = Map.of(
        "free",  10,
        "hobby", 100,
        "pro",   10000
    );

    void example() {
        // All throw on mutation attempts
        // ROLES.add("guest");          // UnsupportedOperationException

        // For maps with more than 10 entries, use Map.ofEntries:
        var huge = Map.ofEntries(
            Map.entry("a", 1),
            Map.entry("b", 2),
            // ... up to as many as you like
            Map.entry("z", 26)
        );

        // Copy any existing collection to immutable form
        List<Integer> mutable = new ArrayList<>(List.of(1, 2, 3));
        List<Integer> frozen  = List.copyOf(mutable);   // snapshot, immutable
        System.out.println(frozen);
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.