Collections Class in Java
The Collections class in Java is a utility class in java.util that contains only static methods for working with collections. It is used to sort, search, reverse, shuffle and fill lists, to find the largest or smallest element, and to create special wrapped collections. Note the difference in names: Collection (singular) is the root interface, while Collections (plural) is this helper class. In this lesson, you will learn the most useful methods of Collections with examples.
Declaration
public class Collections {
private Collections() { } // no objects can be created
// only static methods
}Methods of Collections
| Method | Description |
|---|---|
sort(List<T> list) | It is used to sort a list in natural order. |
sort(List<T> list, Comparator c) | It sorts a list with a comparator. |
reverse(List<?> list) | It reverses the order of a list. |
shuffle(List<?> list) | It puts the elements in a random order. |
swap(List<?> list, int i, int j) | It swaps two elements. |
max(Collection c) / min(Collection c) | It returns the largest or smallest element. |
frequency(Collection c, Object o) | It counts how many times an element appears. |
binarySearch(List list, T key) | It finds an element in a sorted list quickly. |
fill(List<T> list, T value) | It replaces every element with one value. |
nCopies(int n, T value) | It returns an unmodifiable list of n copies. |
addAll(Collection c, T... elements) | It adds several elements at once. |
disjoint(Collection a, Collection b) | It returns true if the two have no element in common. |
unmodifiableList(List l) | It returns a read-only view of a list. |
synchronizedList(List l) | It returns a thread-safe wrapper of a list. |
emptyList(), singletonList(o) | It returns an empty or one-element unmodifiable list. |
Example: Sorting, Searching and Counting
Let's see an example of the everyday methods.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
List<Integer> marks = new ArrayList<>();
Collections.addAll(marks, 78, 91, 85, 60, 91);
System.out.println("Max: " + Collections.max(marks)
+ ", min: " + Collections.min(marks));
System.out.println("91 appears " + Collections.frequency(marks, 91)
+ " times");
Collections.sort(marks);
System.out.println("Sorted: " + marks);
System.out.println("Index of 85: "
+ Collections.binarySearch(marks, 85));
Collections.reverse(marks);
System.out.println("Reversed: " + marks);
Collections.swap(marks, 0, marks.size() - 1);
System.out.println("Swapped ends: " + marks);
}
}Max: 91, min: 60
91 appears 2 times
Sorted: [60, 78, 85, 91, 91]
Index of 85: 2
Reversed: [91, 91, 85, 78, 60]
Swapped ends: [60, 91, 85, 78, 91]Explanation: addAll fills the list in one call. max, min and frequency work on any collection. binarySearch needs a sorted list, so it is called after sort; it found 85 at index 2. reverse and swap rearrange the list in place.
Example: Special Lists
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SpecialLists {
public static void main(String[] args) {
List<String> blanks = Collections.nCopies(3, "-");
System.out.println(blanks);
List<String> names = new ArrayList<>(List.of("Navika", "Srihitha"));
List<String> readOnly = Collections.unmodifiableList(names);
try {
readOnly.add("Advitha");
} catch (UnsupportedOperationException e) {
System.out.println("read-only view rejected add");
}
System.out.println("No common names? " + Collections.disjoint(
names, List.of("Advitha", "Anamaneni")));
System.out.println(Collections.emptyList().size());
}
}[-, -, -]
read-only view rejected add
No common names? true
0Explanation: nCopies makes a list of repeated values. unmodifiableList returns a view that rejects changes. disjoint checks that two collections share no elements, and emptyList returns a shared, empty, unmodifiable list.
Common Mistakes
Calling binarySearch on an unsorted list. The result is undefined; sort first.
Confusing Collection and Collections. One is an interface you implement or declare; the other is a utility class you call.
Calling sort on List.of(...) or nCopies(...). They're unmodifiable and throw UnsupportedOperationException.
Practice
- Easy: Create a list of ten numbers, shuffle it, print it, then print its largest and smallest values.
- Harder: Write a method that returns
trueif two lists contain exactly the same elements with the same counts, in any order, usingCollections.frequency.
Key Takeaways
Was this tutorial helpful?