Collection Algorithms
Java provides a powerful set of built-in algorithms that work directly on
collections like List, Set, and Map.
These algorithms help you perform common operations such as sorting, searching, reversing, and finding minimum or maximum values without writing complex logic.
Where Collection Algorithms Live
Most collection algorithms are provided by the
Collections utility class in the java.util package.
They are static methods, meaning you can use them directly without creating an object.
Sorting a Collection
Sorting is one of the most commonly used collection algorithms.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
List numbers = new ArrayList<>();
numbers.add(45);
numbers.add(10);
numbers.add(30);
numbers.add(5);
Collections.sort(numbers);
System.out.println(numbers);
}
}
The list is sorted in ascending order automatically.
Sorting in Reverse Order
You can also sort collections in descending order.
Collections.sort(numbers, Collections.reverseOrder());
System.out.println(numbers);
Searching Elements
Java provides a fast binary search algorithm for sorted lists.
Collections.sort(numbers);
int index = Collections.binarySearch(numbers, 30);
System.out.println("Found at index: " + index);
Binary search works only on sorted collections.
Finding Minimum and Maximum
You can quickly find the smallest and largest values in a collection.
int min = Collections.min(numbers);
int max = Collections.max(numbers);
System.out.println("Min: " + min);
System.out.println("Max: " + max);
Reversing a Collection
Sometimes data needs to be processed in reverse order.
Collections.reverse(numbers);
System.out.println(numbers);
Shuffling Elements
Shuffling randomizes the order of elements. This is commonly used in games and testing.
Collections.shuffle(numbers);
System.out.println(numbers);
Real-World Example
Consider an online exam system where student scores need to be analyzed.
List scores = new ArrayList<>();
scores.add(78);
scores.add(92);
scores.add(85);
scores.add(60);
Collections.sort(scores);
System.out.println("Top Score: " + Collections.max(scores));
System.out.println("Lowest Score: " + Collections.min(scores));
Collection algorithms simplify complex operations with minimal code.
Why Collection Algorithms Matter
- Reduce boilerplate code
- Improve performance and readability
- Provide tested and optimized logic
- Commonly used in enterprise applications
Key Takeaways
- Collections class provides powerful algorithms
- Sorting, searching, and reversing are easy
- Algorithms work seamlessly with lists
- Essential knowledge for Java developers
In the next lesson, we will build a Collections Mini Project to apply everything learned so far.