Java
Collections class
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.
Exercise 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));.
Show example 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));
}
}
Test yourself
-
Match the Collections methods
- sort(list)
- Sorts
- reverse(list)
- Reverses
- max(list)
- Largest element
- frequency(list, e)
- Returns count
-
Complete the sort call
Collections.____(nums);
Show answer
Collections.sort(nums);
-
When does Collections.binarySearch work correctly?
- When the list is empty
- When the list is sorted
- When the list is a Set
- Always regardless of the list
Show answer
When the list is sorted — binarySearch returns correct results only on a sorted list.
Next lesson: Summary - Generic collections