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 map creation | java.evolved

Home / Collections / Immutable map creation
Collections Beginner

Immutable map creation

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

Create immutable maps inline without a builder.

Collections
Code Comparison
✕ 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);
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
📏

Inline creation

No temporary mutable map needed.

🔒

Immutable result

The map cannot be modified after creation.

🚫

No null keys/values

Null entries are rejected immediately.

Old Approach
Map Builder Pattern
Modern Approach
Map.of()
Since JDK
9
Difficulty
Beginner
JDK Support
Immutable map creation
Available

Widely available since JDK 9 (Sept 2017)

How it works

Map.of() accepts key-value pairs inline and returns an immutable map. For more than 10 entries, use Map.ofEntries() with Map.entry() pairs.

Related Documentation
Map.of() ↗ Map.ofEntries() ↗
Proof
View proof source ↗
Related patterns
Collections Beginner

Copying collections immutably

Java 8
List<String> copy =
    Collections.unmodifiableList(
        new ArrayList<>(original)
    );
Java 10+
List<String> copy =
    List.copyOf(original);
Hover to see modern ➜
JDK 10+ →
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+ →
Streams Beginner

Stream.toList()

Java 8
List<String> result = stream
    .filter(s -> s.length() > 3)
    .collect(Collectors.toList());
Java 16+
List<String> result = stream
    .filter(s -> s.length() > 3)
    .toList();
Hover to see modern ➜
JDK 16+ →
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.