Collections Class
The java.util.Collections class provides static methods for operating on collections. It contains algorithms and wrappers for collections.
Algorithms
Section titled “Algorithms”// SortingList<String> list = new ArrayList<>(Arrays.asList("banana", "apple", "cherry"));Collections.sort(list); // Natural ordering: ["apple", "banana", "cherry"]Collections.sort(list, Collections.reverseOrder()); // Reverse: ["cherry", "banana", "apple"]
// Searching (requires sorted list for binary search)int index = Collections.binarySearch(list, "banana"); // Returns index or negative insertion point
// ShufflingCollections.shuffle(list); // Random orderCollections.shuffle(list, new Random(42)); // Deterministic shuffle with seed
// Min/MaxString min = Collections.min(list); // Smallest elementString max = Collections.max(list); // Largest elementString customMin = Collections.min(list, Comparator.comparing(String::length)); // Custom comparison
// Frequency and disjointint count = Collections.frequency(list, "apple"); // Count occurrencesboolean disjoint = Collections.disjoint(list, Arrays.asList("orange", "grape")); // No common elements?
// Fill, copy, replaceCollections.fill(list, "element"); // Replace all elementsList<String> dest = Arrays.asList(new String[list.size()]);Collections.copy(dest, list); // Copy source to destination (must be same size or larger)Collections.replaceAll(list, "old", "new"); // Replace all occurrences
// RotationCollections.rotate(list, 2); // Rotate right by 2 positionsUnmodifiable Wrappers
Section titled “Unmodifiable Wrappers”Returns a read-only view of the collection. Any attempt to modify will throw UnsupportedOperationException.
List<String> modifiableList = new ArrayList<>(Arrays.asList("a", "b", "c"));List<String> unmodifiableList = Collections.unmodifiableList(modifiableList);
// These will throw UnsupportedOperationException// unmodifiableList.add("d");// unmodifiableList.remove("a");
// Changes to the original collection are visible through the wrappermodifiableList.add("d"); // unmodifiableList now contains ["a", "b", "c", "d"]
// Other unmodifiable wrappersSet<String> unmodifiableSet = Collections.unmodifiableSet(new HashSet<>());Map<String, Integer> unmodifiableMap = Collections.unmodifiableMap(new HashMap<>());Synchronized Wrappers
Section titled “Synchronized Wrappers”Returns a thread-safe view of the collection. All methods are synchronized.
List<String> list = new ArrayList<>();List<String> syncList = Collections.synchronizedList(list);
// Thread-safe accesssynchronized(syncList) { // Always synchronize on the wrapper for iteration for (String item : syncList) { System.out.println(item); }}
// Other synchronized wrappersSet<String> syncSet = Collections.synchronizedSet(new HashSet<>());Map<String, Integer> syncMap = Collections.synchronizedMap(new HashMap<>());Checked Collection Wrappers
Section titled “Checked Collection Wrappers”Provides runtime type checking for collections. Useful when working with legacy code that doesn’t use generics.
List rawList = new ArrayList(); // Raw typeList<String> checkedList = Collections.checkedList(rawList, String.class);
checkedList.add("Safe"); // OK
// This will throw ClassCastException at runtimetry { // Bypassing generics with raw type rawList.add(Integer.valueOf(42));} catch (ClassCastException e) { System.out.println("Type safety violation caught");}Singleton Collections
Section titled “Singleton Collections”Immutable collections with exactly one element.
Set<String> singletonSet = Collections.singleton("element");List<String> singletonList = Collections.singletonList("element");Map<String, Integer> singletonMap = Collections.singletonMap("key", 42);
// Empty collections (immutable)List<String> emptyList = Collections.emptyList();Set<String> emptySet = Collections.emptySet();Map<String, Integer> emptyMap = Collections.emptyMap();