Learnitweb

java.util.Collections

The java.util.Collections class is a utility class in Java that provides static methods for operating on or returning collections such as List, Set, and Map. It is part of the java.util package.

Unlike java.util.Collection (an interface for actual collection objects), Collections contains helper methods to manipulate collection objects, such as sorting, searching, reversing, synchronizing, and creating unmodifiable collections.

1. Key Features of Collections

  1. Utility Class:
    • Collections is a final class with a private constructor.
    • You cannot instantiate it; it only provides static methods.
  2. Collection Manipulation:
    • Provides methods to sort, shuffle, reverse, swap, rotate, and perform other operations on collections.
  3. Thread-Safety Support:
    • Offers methods to wrap collections in synchronized versions for thread-safe operations.
  4. Unmodifiable Collections:
    • Provides methods to create read-only collections that cannot be modified.
  5. Search and Frequency Operations:
    • Provides methods like binarySearch() and frequency() for quick searches and counts.
  6. Algorithm Implementation:
    • Implements common algorithms that can operate on any List or Collection object.

2. Class Declaration

public final class Collections {
    private Collections() {
        // Prevent instantiation
    }
    
    // Static utility methods
}
  • The private constructor ensures that no object of Collections can be created.
  • All its methods are static, so you call them using Collections.methodName().

3. Commonly Used Methods

3.1 Sorting Collections

  • sort(List<T> list): Sorts the elements of a list in natural order (ascending for numbers, alphabetical for strings).
  • sort(List<T> list, Comparator<? super T> c): Sorts using a custom comparator.
List<Integer> numbers = Arrays.asList(5, 2, 9, 1);
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 5, 9]

List<String> names = Arrays.asList("Samir", "Anita", "Ravi");
Collections.sort(names, Comparator.reverseOrder());
System.out.println(names); // [Samir, Ravi, Anita]

3.2 Searching Collections

  • binarySearch(List<? extends Comparable<? super T>> list, T key): Searches for an element in a sorted list using binary search.
  • binarySearch(List<T> list, T key, Comparator<? super T> c): Uses a custom comparator.
List<Integer> nums = Arrays.asList(10, 20, 30, 40, 50);
int index = Collections.binarySearch(nums, 30);
System.out.println(index); // 2

Important: The list must be sorted before using binarySearch(). Otherwise, the result is unpredictable.

3.3 Reversing, Shuffling, and Swapping

  • reverse(List<?> list): Reverses the order of elements in a list.
  • shuffle(List<?> list): Randomly shuffles the elements.
  • swap(List<?> list, int i, int j): Swaps two elements at given positions.
  • rotate(List<?> list, int distance): Rotates elements in a list by a specified distance.
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.reverse(list);
System.out.println(list); // [5, 4, 3, 2, 1]

Collections.shuffle(list);
System.out.println(list); // [2, 5, 3, 1, 4] (random order)

Collections.swap(list, 0, 4);
System.out.println(list); // [4, 5, 3, 1, 2]

Collections.rotate(list, 2);
System.out.println(list); // [1, 2, 4, 5, 3]

3.4 Finding Min, Max, and Frequency

  • min(Collection<? extends T> coll): Returns the minimum element.
  • max(Collection<? extends T> coll): Returns the maximum element.
  • min(Collection<? extends T> coll, Comparator<? super T> c): Min according to a comparator.
  • frequency(Collection<?> c, Object o): Counts occurrences of an element.
List<Integer> nums = Arrays.asList(5, 3, 9, 3, 1);
System.out.println(Collections.min(nums)); // 1
System.out.println(Collections.max(nums)); // 9
System.out.println(Collections.frequency(nums, 3)); // 2

3.5 Thread-Safe Collections

  • Wrap collections in synchronized versions to make them thread-safe:
List<String> list = new ArrayList<>();
List<String> syncList = Collections.synchronizedList(list);
Set<Integer> set = new HashSet<>();
Set<Integer> syncSet = Collections.synchronizedSet(set);
Map<String, Integer> map = new HashMap<>();
Map<String, Integer> syncMap = Collections.synchronizedMap(map);

Thread-safe collections use synchronization wrappers but are not as efficient as concurrent collections (ConcurrentHashMap, CopyOnWriteArrayList) for high-concurrency scenarios.

3.6 Unmodifiable (Read-Only) Collections

  • Create read-only collections to prevent modification:
List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob"));
List<String> readOnlyNames = Collections.unmodifiableList(names);
readOnlyNames.add("Charlie"); // Throws UnsupportedOperationException
  • Similar methods exist for Set and Map:
    • unmodifiableSet(Set<? extends T> s)
    • unmodifiableMap(Map<? extends K, ? extends V> m)

3.7 Other Useful Methods

  • nCopies(int n, T o): Creates a list of n copies of a specified element.
  • emptyList(), emptySet(), emptyMap(): Returns immutable empty collections.
  • singleton(T o): Returns an immutable collection containing only one element.
  • reverseOrder(): Returns a comparator for reverse natural ordering.
List<String> names = Collections.nCopies(3, "Java");
System.out.println(names); // [Java, Java, Java]

Set<Integer> single = Collections.singleton(42);
System.out.println(single); // [42]

4. Performance Notes

  • Methods like sort(), shuffle(), reverse() operate in-place, modifying the original collection.
  • Synchronized wrappers add overhead due to locking; prefer concurrent collections for high-performance multithreading.
  • unmodifiableList is read-only, but if the underlying collection changes, the unmodifiable view reflects the changes. To prevent this, use immutable copies (e.g., List.copyOf() in Java 10+).

5. Practical Use Cases

  1. Sorting a List of Objects
List<Employee> employees = getEmployees();
Collections.sort(employees, Comparator.comparing(Employee::getSalary));
  1. Thread-Safe Access to Shared Collections
List<String> sharedList = Collections.synchronizedList(new ArrayList<>());
  1. Immutable Collections for Safe Sharing
List<String> readOnlyNames = Collections.unmodifiableList(names);
  1. Randomized Operations for Games or Simulations
Collections.shuffle(cards);
  1. Counting Occurrences in a Collection
int count = Collections.frequency(words, "Java");

6. Summary

java.util.Collections is a powerful utility class for:

  • Sorting, reversing, and shuffling collections.
  • Searching, finding min/max, and counting occurrences.
  • Creating synchronized (thread-safe) and unmodifiable collections.
  • Wrapping common algorithms in reusable static methods.

It is one of the most frequently used classes in Java for manipulating collections efficiently and safely.