Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 201 ยท Collections

Immutable Collections and Utility Methods

Learn Java immutable collections - List.of, Set.of, Map.of, copyOf, unmodifiable views, the Collections helper methods and Java 21 sequenced getFirst, getLast and reversed.

So far you've mostly created collections with new ArrayList<>() and filled them one add at a time. That's the right tool for data that changes. But a lot of data never changes after it's created: the days of the week, the list of supported file types, a config value read at startup, a method's return value that callers should only read. For those, Java has unmodifiable collections, created in one expression and protected against accidental changes.

This lesson covers the List.of/Set.of/Map.of factories, copyOf, the difference between an unmodifiable copy and an unmodifiable view, the many small helpers in the Collections class, and the sequenced-collection methods (getFirst, getLast, reversed) that Java 21 added to lists, deques and ordered sets and maps.

List.of, Set.of and Map.of

Since Java 9, the collection interfaces have static factory methods that build small, unmodifiable collections:

Java Creating unmodifiable collections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every method that would change the collection (add, remove, set, put, clear, sort, removeIf ...) throws UnsupportedOperationException. Reading works normally. Map.of takes up to 10 key-value pairs; for more, use Map.ofEntries(Map.entry(k, v), ...).

These collections have strict rules, and each one catches a real bug early:

Rule What happens
No null elements, keys or values NullPointerException at creation
Set.of with duplicate elements IllegalArgumentException at creation
Map.of with duplicate keys IllegalArgumentException at creation
Even asking contains(null) NullPointerException
Set.of/Map.of iteration order unspecified, and deliberately different between JVM runs
Java The strict rules in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because Set.of and Map.of randomize their iteration order on each JVM start, printing them can show a different order every time you press Run. That's intentional: it stops code and tests from relying on an order that was never promised. Use List.of when order matters, or a LinkedHashSet/TreeSet copy for ordered sets.

"Unmodifiable" means the collection's structure can't change. The elements can still be mutable objects. List.of(new StringBuilder("hi")) can't get a new element, but you can still append to the StringBuilder inside it. For a truly immutable collection, store immutable elements such as strings, numbers and records (see Immutable Classes).

copyOf: an unmodifiable snapshot

List.copyOf(collection), Set.copyOf(collection) and Map.copyOf(map) (Java 10) make an unmodifiable copy of existing data. Later changes to the source don't affect the copy. copyOf follows the same null rules, and Set.copyOf quietly drops duplicates instead of throwing.

The classic use is a defensive copy: a class that receives a list from outside and shouldn't be affected if the caller changes it later:

Java
public record Playlist(String name, List<String> songs) {
    public Playlist {
        songs = List.copyOf(songs);   // snapshot; callers can't change it afterward
    }
}

copyOf is also smart: if you pass a collection that's already an unmodifiable List.of/copyOf list, it returns the same object instead of copying again.

Unmodifiable views

The older Collections.unmodifiableList(list) (and unmodifiableSet, unmodifiableMap, unmodifiableCollection) does something different. It returns a read-only view of an existing collection. The view refuses changes, but it shows every change made to the original underneath:

Java View versus copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Views are useful when a class owns a list that keeps changing and wants to let others read it without copying it every time:

Java
class Course {
    private final List<String> students = new ArrayList<>();

    void enroll(String name) { students.add(name); }

    List<String> students() {
        return Collections.unmodifiableList(students);   // live, read-only
    }
}
List.copyOf(x) Collections.unmodifiableList(x)
Changes through it rejected rejected
Later changes to x not visible (snapshot) visible (live view)
Cost copies all elements O(1) wrapper
null elements rejected allowed

Other ways to get read-only lists

  • stream.toList() (Java 16) returns an unmodifiable list. Unlike List.of, it allows null elements. Collectors.toList() makes no promise about mutability (in practice it returns an ArrayList); use Collectors.toCollection(ArrayList::new) when you need to modify the result.
  • Arrays.asList(array) is neither fully modifiable nor unmodifiable: you can set elements (which writes through to the array) but not add or remove. See The Arrays Class.
  • Collections.emptyList(), emptySet(), emptyMap() and singletonList(x), singleton(x), singletonMap(k, v) are older ways to get tiny unmodifiable collections. List.of() and List.of(x) do the same today.

When you need a modifiable collection that starts with some values, wrap the factory: new ArrayList<>(List.of("a", "b")).

The Collections utility class

java.util.Collections (with an "s") is a toolbox of static methods for working with collections. Here are the ones you'll actually use:

Method What it does
sort(list), sort(list, cmp) sorts in place (same as list.sort)
reverse(list) reverses the order in place
shuffle(list), shuffle(list, random) random order; pass a seeded Random for repeatable results
swap(list, i, j) swaps two positions
rotate(list, distance) shifts elements right by distance, wrapping around (negative shifts left)
fill(list, value) replaces every element with value
frequency(c, value) how many times value occurs
max(c), min(c) (optionally with a comparator) the largest or smallest element, in O(n)
nCopies(n, value) an unmodifiable list of n copies of one value
addAll(c, a, b, c...) adds several values in one call
disjoint(c1, c2) true if they have no elements in common
binarySearch(sortedList, key) fast search in a sorted list
reverseOrder(), reverseOrder(cmp) a comparator that reverses natural order or cmp
Java A tour of Collections helpers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

binarySearch returns the index when it finds the key. When it doesn't, it returns -(insertionPoint) - 1: here 20 would be inserted at index 3, so the result is -4. That encoding keeps "not found" negative even when the insertion point is 0. The list must be sorted by the same order you search with, or the answer is meaningless.

Collections also has wrappers like synchronizedList(list) (makes each method call thread-safe, though iteration still needs manual locking) and checkedList(list, String.class) (rejects wrong types at runtime, handy when mixing generic and legacy code). For concurrent code, the classes in Concurrent Collections are usually a better choice.

Sequenced collections (Java 21)

For years, "get the last element" meant something different for every collection: list.get(list.size() - 1), deque.getLast(), sortedSet.last(), and for a LinkedHashSet, a loop through everything. Java 21 unified this with three interfaces (introduced in The Collections Framework):

  • SequencedCollection: List, Deque, LinkedHashSet, SortedSet/TreeSet and friends.
  • SequencedSet: the ordered sets.
  • SequencedMap: LinkedHashMap, SortedMap/TreeMap.

They share one vocabulary:

Method What it does
getFirst(), getLast() the first or last element; NoSuchElementException if empty
addFirst(e), addLast(e) insert at an end
removeFirst(), removeLast() remove and return an end
reversed() a reverse-ordered view

Maps get firstEntry(), lastEntry(), pollFirstEntry(), pollLastEntry(), putFirst, putLast and reversed() (see LinkedHashMap and LinkedHashSet).

Java getFirst, getLast and reversed views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Points to remember:

  • reversed() is a view. It doesn't copy anything, so it's O(1), and changes through it affect the original, as addFirst("celebrate") shows.
  • Unmodifiable stays unmodifiable. getFirst and reversed work on List.of(...), but addFirst/removeLast throw.
  • Sorted collections can't take position orders. TreeSet.addFirst throws UnsupportedOperationException, because the tree decides where elements go.
  • getFirst on an empty list throws NoSuchElementException, unlike Deque.peekFirst, which returns null.
  • Collections.unmodifiableSequencedCollection, unmodifiableSequencedSet and unmodifiableSequencedMap create read-only views that still offer the sequenced methods.

On Java 21+, prefer list.getLast() to list.get(list.size() - 1) and for (var x : list.reversed()) to a countdown loop. They read better and can't be off by one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you call add on a list created with List.of("a", "b")?

    List.of returns an unmodifiable list. Every mutating method compiles, because it is part of the List interface, but throws at runtime.
  2. 2. List<String> view = Collections.unmodifiableList(names); After names.add("Zoe"), does view contain "Zoe"?

    An unmodifiable view blocks changes through itself but shows changes made to the original list. Use List.copyOf for a snapshot.
  3. 3. What does Set.of("a", "b", "a") do?

    Set.of treats duplicate arguments as a programming error and throws. Set.copyOf or new HashSet<>(...) drop duplicates quietly instead.
  4. 4. For List<String> list = new ArrayList<>(List.of("x", "y")), what does list.reversed().addFirst("z") do to list?

    reversed() is a live view. The first position of the reversed view is the last position of the original, so z is appended to list.
  5. 5. What does Collections.frequency(List.of(1, 2, 1, 1, 3), 1) return?

    frequency counts how many elements are equal to the given value. The value 1 appears three times.

Summary

  • List.of, Set.of, Map.of and Map.ofEntries create small unmodifiable collections; they reject null, and Set.of/Map.of reject duplicates and have no fixed iteration order.
  • List.copyOf, Set.copyOf and Map.copyOf make unmodifiable snapshots, perfect for defensive copies.
  • Collections.unmodifiableList and friends are read-only views that still show changes to the original.
  • stream.toList() is unmodifiable; Arrays.asList is fixed-size; wrap with new ArrayList<>(...) when you need to modify.
  • The Collections class offers sort, reverse, shuffle, swap, rotate, fill, frequency, nCopies, max/min, binarySearch and more.
  • Java 21's sequenced collections give lists, deques and ordered sets and maps getFirst, getLast, addFirst, addLast, removeFirst, removeLast and a live reversed() view.

Next: EnumMap, EnumSet, IdentityHashMap, WeakHashMap and BitSet, the specialized collections that beat the general-purpose ones at particular jobs.