Java provides an array of algorithms in the Collections class to facilitate common data structure manipulations like sorting, searching, reversing, shuffling, and more. These methods allow developers to write efficient and clean code without manually implementing these operations. In this article, we’ll explore some of the most common algorithms available in the Collections class, complete with code examples.
1. Sorting: Collections.sort()
The sort()
method is used to sort a list of elements. It uses the natural ordering of the elements or a custom comparator for sorting. Below is an example using both approaches:
Example – Sorting a List of Integers (Natural Order)
import java.util.*;
public class SortExample {
public static void main(String[] args) {
List numbers = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 3));
Collections.sort(numbers);
System.out.println("Sorted numbers: " + numbers);
}
}
Output: Sorted numbers: [1, 2, 3, 5, 8]
Example – Sorting with a Custom Comparator
import java.util.*;
public class SortWithComparator {
public static void main(String[] args) {
List names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
Collections.sort(names, (s1, s2) -> s2.compareTo(s1)); // Sorting in reverse order
System.out.println("Sorted names: " + names);
}
}
Output: Sorted names: [Charlie, Bob, Alice]
2. Searching: Collections.binarySearch()
The binarySearch()
method is used to search for an element in a sorted list. It returns the index of the element if it’s found or a negative value if not.
Example – Binary Search
import java.util.*;
public class BinarySearchExample {
public static void main(String[] args) {
List sortedList = Arrays.asList(1, 3, 5, 7, 9);
int index = Collections.binarySearch(sortedList, 5);
System.out.println("Index of 5: " + index); // Output: 2
}
}
Output: Index of 5: 2
3. Reversing: Collections.reverse()
The reverse()
method reverses the order of elements in a list.
Example – Reversing a List
import java.util.*;
public class ReverseExample {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry"));
Collections.reverse(list);
System.out.println("Reversed list: " + list);
}
}
Output: Reversed list: [Cherry, Banana, Apple]
4. Shuffling: Collections.shuffle()
The shuffle()
method is used to randomly shuffle the elements of a list.
Example – Shuffling a List
import java.util.*;
public class ShuffleExample {
public static void main(String[] args) {
List deck = new ArrayList<>(Arrays.asList("Ace", "King", "Queen", "Jack"));
Collections.shuffle(deck);
System.out.println("Shuffled deck: " + deck);
}
}
Output: Shuffled deck: [Jack, Ace, Queen, King]
5. Rotating: Collections.rotate()
The rotate()
method rotates the elements of a list by a specified number of positions.
Example – Rotating a List
import java.util.*;
public class RotateExample {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList("One", "Two", "Three", "Four"));
Collections.rotate(list, 2); // Rotates by 2 positions
System.out.println("Rotated list: " + list);
}
}
Output: Rotated list: [Three, Four, One, Two]
6. Frequency Count: Collections.frequency()
The frequency()
method counts the occurrences of an element in a collection.
Example – Frequency Count
import java.util.*;
public class FrequencyExample {
public static void main(String[] args) {
List list = Arrays.asList("apple", "banana", "apple", "orange", "apple");
int frequency = Collections.frequency(list, "apple");
System.out.println("Frequency of 'apple': " + frequency); // Output: 3
}
}
Output: Frequency of ‘apple’: 3
7. Unmodifiable Collections: Collections.unmodifiableList()
With the unmodifiableList()
method, you can create a read-only version of a list, making it immutable.
Example – Unmodifiable List
import java.util.*;
public class UnmodifiableListExample {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList("A", "B", "C"));
List unmodifiableList = Collections.unmodifiableList(list);
System.out.println("Unmodifiable list: " + unmodifiableList);
// unmodifiableList.add("D"); // Throws UnsupportedOperationException
}
}
Output: Unmodifiable list: [A, B, C]
Conclusion
Java’s Collections
class provides a robust set of algorithms that significantly enhance the manipulation of collections. Whether you need to sort, search, shuffle, or count frequencies, these built-in methods can simplify your code and improve performance. By mastering these algorithms, you’ll be able to handle most data manipulation tasks efficiently without reinventing the wheel.