Mastering Java Collection Algorithms: Sorting, Shuffling, and More
Java Algorithms
In this tutorial, we explore the powerful algorithms provided by Java’s Collections framework through clear, hands‑on examples.
The Java Collections framework supplies a rich set of static methods—often called generic algorithms—that let you manipulate data structures without writing boilerplate code. These utilities work with any collection that implements the Collection interface, offering both simplicity and performance.
Below, we walk through the most frequently used algorithms, illustrating their syntax, behavior, and practical use cases.
1. Sorting with Collections.sort()
The sort() method orders elements in natural (ascending) order. For custom ordering, supply a Comparator implementation.
import java.util.ArrayList;
import java.util.Collections;
class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(4);
numbers.add(2);
numbers.add(3);
System.out.println("Unsorted ArrayList: " + numbers);
Collections.sort(numbers);
System.out.println("Sorted ArrayList: " + numbers);
}
}
Output
Unsorted ArrayList: [4, 2, 3] Sorted ArrayList: [2, 3, 4]
For descending order or domain‑specific criteria, use a custom Comparator—see the Java Sorting guide for details.
2. Randomizing Order with Collections.shuffle()
Use shuffle() to randomize the sequence of elements, ideal for games or sampling scenarios.
import java.util.ArrayList;
import java.util.Collections;
class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("Sorted ArrayList: " + numbers);
Collections.shuffle(numbers);
System.out.println("ArrayList after shuffle: " + numbers);
}
}
Output
Sorted ArrayList: [1, 2, 3] ArrayList after shuffle: [2, 1, 3]
Each run produces a different permutation, thanks to the underlying Fisher‑Yates algorithm.
3. Routine Data Manipulation
Java offers a suite of utility methods to transform collections:
reverse()– reverse the element order.fill()– replace every element with a specified value.copy()– copy elements from one collection to another (sized the same).swap()– exchange two elements by index.addAll()– append all elements from one collection to another.
import java.util.ArrayList;
import java.util.Collections;
class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
System.out.println("ArrayList1: " + numbers);
Collections.reverse(numbers);
System.out.println("Reversed ArrayList1: " + numbers);
Collections.swap(numbers, 0, 1);
System.out.println("ArrayList1 after swap(): " + numbers);
ArrayList<Integer> newNumbers = new ArrayList<>();
newNumbers.addAll(numbers);
System.out.println("ArrayList2 using addAll(): " + newNumbers);
Collections.fill(numbers, 0);
System.out.println("ArrayList1 after fill(): " + numbers);
Collections.copy(newNumbers, numbers);
System.out.println("ArrayList2 after copy(): " + newNumbers);
}
}
Output
ArrayList1: [1, 2] Reversed ArrayList1: [2, 1] ArrayList1 after swap(): [1, 2] ArrayList2 using addAll(): [1, 2] ArrayList1 after fill(): [0, 0] ArrayList2 after copy(): [0, 0]
Note: The copy() method requires that the destination collection has at least as many elements as the source.
4. Binary Search with Collections.binarySearch()
Efficiently locate an element in a sorted collection. The method returns the index of the element or a negative insertion point if not found.
import java.util.ArrayList;
import java.util.Collections;
class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
int pos = Collections.binarySearch(numbers, 3);
System.out.println("The position of 3 is " + pos);
}
}
Output
The position of 3 is 2.
Tip: Always sort the collection before calling binarySearch(); otherwise the result is undefined.
Explore more in the Java Binary Search article.
5. Collection Composition
These utilities analyze relationships between collections:
frequency()– count occurrences of a specific element.disjoint()– check if two collections share no common elements.
import java.util.ArrayList;
import java.util.Collections;
class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(2);
System.out.println("ArrayList1: " + numbers);
int count = Collections.frequency(numbers, 2);
System.out.println("Count of 2: " + count);
ArrayList<Integer> newNumbers = new ArrayList<>();
newNumbers.add(5);
newNumbers.add(6);
System.out.println("ArrayList2: " + newNumbers);
boolean disjoint = Collections.disjoint(numbers, newNumbers);
System.out.println("Two lists are disjoint: " + disjoint);
}
}
Output
ArrayList1: [1, 2, 3, 2] Count of 2: 2 ArrayList2: [5, 6] Two lists are disjoint: true
6. Finding Minimum and Maximum
Retrieve the smallest or largest element with min() and max()—useful for analytics and boundary checks.
import java.util.ArrayList;
import java.util.Collections;
class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
int min = Collections.min(numbers);
System.out.println("Minimum Element: " + min);
int max = Collections.max(numbers);
System.out.println("Maximum Element: " + max);
}
}
Output
Minimum Element: 1 Maximum Element: 3
Java
- Master Java Operators: Types, Syntax, & Practical Examples
- Java List Interface: Overview, Implementations, and Key Methods
- Mastering Java ArrayList: Operations, Methods, and Best Practices
- Java TreeMap: Master Sorted Maps with Practical Examples
- Mastering Java ConcurrentHashMap: Operations, Examples, and Best Practices
- Java HashSet Class: Complete Guide to Operations, Methods, and Set Theory
- Mastering Java TreeSet: Operations, Methods, and Practical Examples
- Java ArrayList Explained: Usage, Key Methods, and Practical Examples
- Generate Random Numbers in Java: Practical Guide with Random and Math.random
- Java Numbers Class – Wrapper Classes & Inheritance Explained