The Collections Class
sort(), reverse(), max(), and min()
sort(), reverse(), max(), min()
import java.util.ArrayList; import java.util.Collections; import java.util.List; List<Integer> numbers = new ArrayList<>(List.of(5, 2, 8, 1, 9, 3)); Collections.sort(numbers); System.out.println(numbers); Collections.reverse(numbers); System.out.println(numbers); System.out.println(Collections.max(numbers)); System.out.println(Collections.min(numbers));
[1, 2, 3, 5, 8, 9] [9, 8, 5, 3, 2, 1] 9 1
unmodifiableList() — Read-Only Views
unmodifiableList() protects against accidental mutation
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
List<String> mutable = new ArrayList<>(List.of("a", "b", "c"));
List<String> readOnlyView = Collections.unmodifiableList(mutable);
System.out.println(readOnlyView);
try {
readOnlyView.add("d"); // throws UnsupportedOperationException
} catch (UnsupportedOperationException e) {
System.out.println("Blocked: " + e.getClass().getSimpleName());
}[a, b, c] Blocked: UnsupportedOperationException
synchronizedList() — A Teaser
Wrapping a list for thread-safe access
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
List<String> threadSafeList =
Collections.synchronizedList(new ArrayList<>());
threadSafeList.add("safe to call from multiple threads");
System.out.println(threadSafeList);[safe to call from multiple threads]
emptyList() and singletonList()
emptyList() and singletonList()
import java.util.Collections;
import java.util.List;
List<String> nothing = Collections.emptyList();
List<String> justOne = Collections.singletonList("only-value");
System.out.println(nothing);
System.out.println(justOne);[] [only-value]
Method | Purpose |
|---|---|
Collections.sort(list) | Sort in place (natural order or Comparator) |
Collections.reverse(list) | Reverse the order in place |
Collections.max()/min() | Find the largest/smallest element |
Collections.unmodifiableList() | Read-only view over an existing list |
Collections.synchronizedList() | Thread-safe wrapper around a list |
Collections.emptyList()/singletonList() | Efficient tiny immutable lists |
Collections (class) is a utility toolbox; Collection (interface) is the root of the hierarchy
sort(), reverse(), max(), and min() are the everyday workhorses
unmodifiableList() returns a read-only view, not a copy
synchronizedList() adds thread-safe method calls, foreshadowing the concurrency pages
emptyList()/singletonList() avoid overhead for trivially small lists