🧰 Introduction
The Collections class in Java is part of the java.util package. It consists exclusively of static methods that operate on or return collections (like List, Set, etc.). These methods are useful for sorting, searching, shuffling, and thread-safety operations.
✅ Collections ≠ Collection
Collection is an interface, while Collections is a utility/helper class.
📦 Commonly Used Methods in Collections Class
Method | Description |
|---|---|
| Sorts the elements of a list |
| Reverses the order of elements in a list |
| Randomly permutes the elements |
| Returns the max/min element |
| Returns the number of times an element appears |
| Swaps two elements in a list |
| Searches the list using binary search |
| Replaces all elements with a specified value |
| Copies elements from one list to another |
| Returns thread-safe version of list |
✅ Example Program Using Common Methods
import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 8, 1, 9));
// Sort the list
Collections.sort(numbers);
System.out.println("Sorted: " + numbers);
// Reverse the list
Collections.reverse(numbers);
System.out.println("Reversed: " + numbers);
// Shuffle the list
Collections.shuffle(numbers);
System.out.println("Shuffled: " + numbers);
// Find max and min
System.out.println("Max: " + Collections.max(numbers));
System.out.println("Min: " + Collections.min(numbers));
// Frequency
numbers.add(3);
System.out.println("Frequency of 3: " + Collections.frequency(numbers, 3));
// Swap elements
Collections.swap(numbers, 0, 2);
System.out.println("After swapping 0 and 2: " + numbers);
}
}Sorted: [1, 3, 5, 8, 9]
Reversed: [9, 8, 5, 3, 1]
Shuffled: [5, 9, 3, 8, 1]
Max: 9
Min: 1
Frequency of 3: 1
After swapping 0 and 2: [3, 9, 5, 8, 1]Shuffle output may change every time you run the program.
🧠 When to Use Collections Class?
To sort or reverse a list easily
To search for elements in a sorted list
To perform data analysis using
frequency,max,minTo make collections thread-safe
To implement randomization features (like cards, shuffling questions)
🧪 Advanced: Thread-safe Collection
List<String> threadSafeList = Collections.synchronizedList(new ArrayList<>());This is useful in multi-threaded environments to avoid ConcurrentModificationException.