Collections class
- Java course
- Intermediate
- Lesson 92/116
- 5 min
Learn Collections.sort and frequency helpers.
The Collections helper class
Collections (plural) provides static helper methods on collections. To sort a list use Collections.sort(list); to reverse use Collections.reverse(list); to shuffle use Collections.shuffle(list).
These methods mutate the list in place; they do not return a new list. Collections.max(list) returns the largest, Collections.min(list) the smallest element. Collections.frequency(list, e) counts how many times an element appears.
Sorting and searching
Once a list is sorted you can search fast with Collections.binarySearch(list, key). Binary search works correctly only on a sorted list; on an unsorted one the result is undefined.
The index of the found element is returned; if absent a negative number is returned. Collections.emptyList() returns an empty immutable list, useful as a safe default instead of null. Collections.unmodifiableList(list) wraps a list as read-only.
Practice Sort and find the number list
Declare List<Integer> nums = new ArrayList<>();. Add three numbers with nums.add(30);, nums.add(10); and nums.add(20);. Sort with Collections.sort(nums);. Print the first element with System.out.println(nums.get(0)); and the largest with System.out.println(Collections.max(nums));.
Starter code
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
// Declare List<Integer>, add three numbers, sort, print first and max
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>();
nums.add(30);
nums.add(10);
nums.add(20);
Collections.sort(nums);
System.out.println(nums.get(0));
System.out.println(Collections.max(nums));
}
}Expected output
10 30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Collections methods
| Term | Meaning |
|---|---|
sort(list) |
Sorts |
reverse(list) |
Reverses |
max(list) |
Largest element |
frequency(list, e) |
Returns count |
2 Complete the sort call
Collections.____(nums);
Collections.sort(nums);
Explanation: The sort method orders the list from small to large.
3 When does Collections.binarySearch work correctly?
- When the list is empty
- When the list is sorted Correct answer
- When the list is a Set
- Always regardless of the list
Explanation: binarySearch returns correct results only on a sorted list.