Course contentsShow
← Java
Lesson 1557 of 2,87034. Collectors in DepthFree lesson

toUnmodifiableSet() and toUnmodifiableMap()

Create immutable sets and maps with toUnmodifiableSet() and toUnmodifiableMap() for thread-safe results.

toUnmodifiableSet() and toUnmodifiableMap()

What You'll Learn

You'll learn how to create thread-safe, immutable sets and maps directly from streams using specialized collectors.

The Core Idea

Just as toUnmodifiableList() creates an immutable list, Java provides Collectors.toUnmodifiableSet() and Collectors.toUnmodifiableMap() to create immutable sets and maps. These collectors return collections that cannot be modified after creation—no adding, removing, or changing elements. Any attempt throws an UnsupportedOperationException.

Why does this matter? Immutable collections are inherently thread-safe, making them perfect for concurrent environments or when you want to guarantee data won't change after collection.

toUnmodifiableSet() in Action

Set<String> immutableSet = Stream.of("apple", "banana", "apple", "cherry")
    .collect(Collectors.toUnmodifiableSet());

// immutableSet contains: ["apple", "banana", "cherry"]
// immutableSet.add("date"); // UnsupportedOperationException!

Like regular sets, duplicates are automatically removed.

toUnmodifiableMap() in Action

Map<Integer, String> immutableMap = Stream.of("apple", "banana", "cherry")
    .collect(Collectors.toUnmodifiableMap(
        String::length,      // key mapper
        String::toUpperCase  // value mapper
    ));

// immutableMap: {5=APPLE, 6=BANANA, 6=CHERRY} 
// Wait—duplicate key 6! This throws IllegalStateException

Remember: use a merge function if duplicate keys are possible, just like with regular toMap().

Map<Integer, String> safeMap = Stream.of("apple", "banana", "cherry")
    .collect(Collectors.toUnmodifiableMap(
        String::length,
        String::toUpperCase,
        (existing, replacement) -> existing  // keep first
    ));

Key Takeaway: Use toUnmodifiableSet() and toUnmodifiableMap() when you need immutable, thread-safe collections from streams—they prevent accidental modification and are ideal for defensive programming and concurrent scenarios.