The Java Collections Framework includes a utility class named java.util.Collections (with an 's' at the end) that consists exclusively of static methods that operate on or return collections.
This class provides a set of powerful, reusable algorithms that can save you a lot of time and effort.
Collections.sort()The sort() method sorts the elements of a List into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface.
import java.util.ArrayList; import java.util.Collections; import java.util.List;public class Main { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Charlie"); names.add("Alice"); names.add("Bob"); System.out.println("Original list: " + names); Collections.sort(names); System.out.println("Sorted list: " + names); } }
Collections.shuffle()The shuffle() method randomly permutes the specified list. This is useful for games, simulations, or any application where you need to randomize the order of elements.
import java.util.ArrayList; import java.util.Collections; import java.util.List;public class Main { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); for (int i = 1; i <= 5; i++) { numbers.add(i); } System.out.println("Original list: " + numbers); Collections.shuffle(numbers); System.out.println("Shuffled list: " + numbers); } }
The Collections class provides many other useful static methods.
| Method | Description |
|---|---|
reverse(List<?> list) |
Reverses the order of the elements in the specified list. |
binarySearch(List<?> list, T key) |
Searches the specified list for an object using the binary search algorithm. The list must be sorted beforehand. |
max(Collection<?> coll) |
Returns the maximum element of the given collection, according to the natural ordering of its elements. |
min(Collection<?> coll) |
Returns the minimum element of the given collection. |
fill(List<?> list, T obj) |
Replaces all of the elements of the specified list with the specified element. |
frequency(Collection<?> c, Object o) |
Returns the number of times the specified object occurs in the specified collection. |
import java.util.ArrayList; import java.util.Collections; import java.util.List;public class Main { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(50); numbers.add(20); System.out.println("Max element: " + Collections.max(numbers)); System.out.println("Min element: " + Collections.min(numbers)); Collections.reverse(numbers); System.out.println("Reversed list: " + numbers); } }