Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Collections Class: Sorting and Synchronization

Learn how to use the java.util.Collections class for sorting, shuffling, unmodifiable views, and synchronized collections, with code examples and key trade-offs.

~5 min readJava
#Java#Collections#Sorting#Synchronization
Java Collections class utility methods illustrated with sorting and synchronization icons over a collection diagram

The java.util.Collections class is a utility class that provides static methods for sorting, shuffling, and wrapping collections. It is not a collection type itself, but a container for algorithms that work with the standard collection interfaces. Its methods complement List, Set, and Map implementations, so you can apply common operations without reimplementing them. This article covers the most practical methods and explains their behavior, trade-offs, and thread-safety considerations.

What the Collections Class Does

The Collections class is a container for static utility methods, not a collection. It operates on objects that implement the relevant collection interfaces. For example, Collections.sort() accepts a List, while Collections.min() works with any Collection. Keeping algorithms separate from data structures lets you reuse the same operations across different implementations, such as ArrayList, LinkedList, and HashSet.

A practical benefit is that the class provides a consistent API for operations that are easy to get wrong. Sorting a list with a custom comparator, for instance, is a single method call rather than a hand-written sort.

Sorting with Collections.sort

Collections.sort() sorts a List into ascending order. It uses the natural ordering of the elements if they implement Comparable, or a Comparator that you supply. The sort modifies the original list in place; it does not return a new list. If you want to keep the original order, copy the list before sorting.

java
List<String> names = new ArrayList<>(); names.add("Charlie"); names.add("Alice"); names.add("Bob"); Collections.sort(names); System.out.println(names); // [Alice, Bob, Charlie]

For custom objects, pass a comparator:

java
List<Employee> employees = getEmployees(); Collections.sort(employees, Comparator.comparing(Employee::getLastName));

If the elements do not implement Comparable and no Comparator is supplied, the sort will throw a ClassCastException when it encounters the first incompatible element. As of modern Java, the underlying sort for objects is a stable, adaptive merge sort (TimSort) with O(n log n) worst-case time.

Shuffling and Reordering Elements

Collections.shuffle() randomly permutes a List using a default Random instance. It is useful for games, randomized test data, or any place where elements should appear in a different order. You can also pass your own Random to make the shuffle reproducible.

java
List<Integer> numbers = new ArrayList<>(); for (int i = 1; i <= 10; i++) { numbers.add(i); } Collections.shuffle(numbers); System.out.println(numbers); // e.g., [4, 9, 2, 7, 1, 5, 10, 3, 8, 6]

The shuffle runs in linear time. The default randomness is not suitable for cryptographic operations.

Creating Unmodifiable Collections

The Collections class provides unmodifiableList, unmodifiableSet, unmodifiableMap, and related methods. These methods return a read-only wrapper around an existing collection. Any attempt to modify the collection through the wrapper throws UnsupportedOperationException.

java
List<String> mutableList = new ArrayList<>(); mutableList.add("one"); mutableList.add("two"); List<String> unmodifiableList = Collections.unmodifiableList(mutableList); unmodifiableList.add("three"); // Throws UnsupportedOperationException

The wrapper shares data with the original collection. If you still hold a reference to the original and modify it, the wrapper will reflect those changes. To prevent this, copy the data before wrapping:

java
List<String> unmodifiableCopy = Collections.unmodifiableList(new ArrayList<>(mutableList));

This pattern is useful when a class returns an internal collection without allowing external callers to change it. Note that an unmodifiable wrapper only prevents changes to the collection structure; it does not make the elements themselves immutable.

Synchronized Collections for Thread Safety

Collections.synchronizedList, synchronizedSet, and synchronizedMap return collection views synchronized on an internal mutex. Every method in the wrapped collection is synchronized, which makes these wrappers a simple option for thread safety. The cost is lock acquisition on every operation.

java
List<String> syncList = Collections.synchronizedList(new ArrayList<>());

Iterating over a synchronized collection still requires manual synchronization around the entire iteration. Otherwise, another thread can modify the collection between calls to next(), which can lead to a ConcurrentModificationException.

java
synchronized (syncList) { for (String item : syncList) { // process item } }

Synchronized wrappers are acceptable when concurrency is low. For higher throughput, prefer collections from java.util.concurrent such as CopyOnWriteArrayList or ConcurrentHashMap, which provide better scalability for specific access patterns.

Finding Extremes: min and max

Collections.min() and Collections.max() find the smallest or largest element in a collection, using natural ordering or a supplied Comparator. They work on any Collection, including Set and Queue, and run in linear time through the elements.

java
List<Integer> scores = Arrays.asList(42, 17, 89, 63); int highest = Collections.max(scores); int lowest = Collections.min(scores); System.out.println("Highest: " + highest + ", Lowest: " + lowest);

Both methods throw NoSuchElementException if the collection is empty.

Performance Considerations and Trade-offs

The performance of Collections methods depends on the underlying collection and the wrapper you choose. Collections.sort() only works on List; sets and maps are not lists and cannot be reordered by this method. When choosing a list implementation for sorting, prefer ArrayList. An ArrayList can sort its internal array directly. A LinkedList uses the default List.sort behavior in most JDK versions: it copies the elements into an array, sorts them, and writes them back through a list iterator, which adds traversal overhead.

Unmodifiable wrappers add minimal overhead for read operations because they delegate to the underlying collection. The main cost is a check that throws UnsupportedOperationException for mutating calls. Synchronized wrappers, by contrast, lock on every method call and can become a bottleneck.

Another design point is that Collections methods are static and cannot be overridden or extended. If you need custom behavior, implement your own utility code or use the default methods added to collection interfaces in Java 8 and later. For example, List.sort() is a default method, and Collections.sort() delegates to it, so myList.sort(comparator) is a more direct option in code that already has a List.

Choose between an unmodifiable view and a synchronized collection based on the actual requirement. If you need to prevent modification, use an unmodifiable wrapper. If you need thread safety, use a synchronized wrapper or a concurrent collection. The two concerns are separate; you can wrap a synchronized list in an unmodifiable view if needed, but avoid exposing the original mutable reference.

A practical read-only pattern is to copy the data into an unmodifiable wrapper once the collection is built. If the elements themselves are safe to share, this avoids synchronization because no code can change the collection structure afterward. The List.of() and Set.of() factory methods added in Java 9 are more concise ways to create immutable collections, but they do not accept null elements and are not available for every collection type.

The Collections class remains an important part of Java's collection ecosystem. Its methods are easy to call, but they require an understanding of in-place modifications, wrapper views, and synchronization rules to avoid performance problems and concurrency bugs. Knowing when to use sorting, shuffling, unmodifiable views, and synchronized wrappers helps you write robust and maintainable Java code.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.