GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Immutable list creation | java.evolved

Home / Collections / Immutable list creation
Collections Beginner

Immutable list creation

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Create immutable lists in one clean expression.

Collections
Code Comparison
✕ Java 8
List<String> list =
    Collections.unmodifiableList(
        new ArrayList<>(
            Arrays.asList("a", "b", "c")
        )
    );
✓ Java 9+
List<String> list =
    List.of("a", "b", "c");
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
📏

One call

Replace three nested calls with a single factory method.

🔒

Truly immutable

Not just a wrapper — the list itself is immutable.

🛡️

Null-safe

Rejects null elements at creation time, failing fast.

Old Approach
Verbose Wrapping
Modern Approach
List.of()
Since JDK
9
Difficulty
Beginner
JDK Support
Immutable list creation
Available

Widely available since JDK 9 (Sept 2017)

How it works

List.of() creates a truly immutable list — no wrapping, no defensive copy. It's null-hostile (rejects null elements) and structurally immutable. The old way required three nested calls.

Related Documentation
List.of() ↗ Collections Factory Methods (JEP 269) ↗
Proof
View proof source ↗
Related patterns
Collections Beginner

Immutable map creation

Java 8
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map = Collections.unmodifiableMap(map);
Java 9+
Map<String, Integer> map =
    Map.of("a", 1, "b", 2, "c", 3);
Hover to see modern ➜
JDK 9+ →
Collections Beginner

Immutable set creation

Java 8
Set<String> set =
    Collections.unmodifiableSet(
        new HashSet<>(
            Arrays.asList("a", "b", "c")
        )
    );
Java 9+
Set<String> set =
    Set.of("a", "b", "c");
Hover to see modern ➜
JDK 9+ →
Collections Beginner

Sequenced collections

Java 8
// Get last element
Object last = list.get(list.size() - 1);
// Get first
Object first = list.get(0);
// Reverse iteration: manual
Java 21+
var last = list.getLast();
var first = list.getFirst();
var reversed = list.reversed();
Hover to see modern ➜
JDK 21+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.