Syntax
Collections.methodName(collection);Examples
Sorting and Reversing
Common list-ordering operations.
import java.util.ArrayList;
import java.util.Collections;
ArrayList<Integer> numbers = new ArrayList<>(java.util.List.of(5, 2, 8, 1, 9));
Collections.sort(numbers);
System.out.println(numbers); // [1, 2, 5, 8, 9]
Collections.reverse(numbers);
System.out.println(numbers); // [9, 8, 5, 2, 1]Finding min, max, and frequency
Quickly computing summary statistics over a collection.
import java.util.ArrayList;
import java.util.Collections;
ArrayList<Integer> scores = new ArrayList<>(java.util.List.of(85, 92, 78, 92, 90));
System.out.println(Collections.max(scores)); // 92
System.out.println(Collections.min(scores)); // 78
System.out.println(Collections.frequency(scores, 92)); // 2Creating Unmodifiable Collections
Wrapping a collection to prevent any further modification, useful for defensive programming.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
ArrayList<String> mutable = new ArrayList<>(java.util.List.of("a", "b", "c"));
List<String> readOnly = Collections.unmodifiableList(mutable);
System.out.println(readOnly); // [a, b, c]
try {
readOnly.add("d"); // throws UnsupportedOperationException
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify - it's read-only");
}Shuffling and Empty Collections
Randomizing element order, and getting properly typed empty collections.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
ArrayList<Integer> deck = new ArrayList<>(java.util.List.of(1, 2, 3, 4, 5));
Collections.shuffle(deck);
System.out.println(deck); // random order each run
List<String> empty = Collections.emptyList();
System.out.println(empty.size()); // 0Best practices
- Use Collections.unmodifiableList()/Set()/Map() to safely expose internal collections from a class without allowing external code to modify them
- Use Collections.sort() with a custom Comparator for sorting by criteria other than natural ordering
- Use Collections.emptyList()/emptySet()/emptyMap() instead of creating a new empty ArrayList/HashSet/HashMap when you just need an immutable, empty placeholder
- Don't confuse Collections (the utility class, plural) with Collection (the root interface, singular) - they serve very different purposes
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification