Collections framework · Topic 8 of 8
Collections utility methods
Definition​
The Collections class has ready-made helpers for lists and other collections: sorting, shuffling with a seed, counting, finding the largest, reversing, and creating read-only views.
Example code​
Handy one-liners
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
class Demo {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(4, 8, 15, 16, 23, 42, 8));
System.out.println(Collections.max(numbers) + " " + Collections.min(numbers));
System.out.println(Collections.frequency(numbers, 8)); // how many 8s
Collections.sort(numbers);
System.out.println(numbers + " -> index of 23: " + Collections.binarySearch(numbers, 23));
Collections.reverse(numbers);
System.out.println(numbers);
Collections.shuffle(numbers, new Random(1)); // a seed makes it repeatable
System.out.println(numbers);
List<Integer> readOnly = Collections.unmodifiableList(numbers);
System.out.println(readOnly.size());
System.out.println(Collections.nCopies(3, "ha"));
}
}
// Output:
// 42 4
// 2
// [4, 8, 8, 15, 16, 23, 42] -> index of 23: 5
// [42, 23, 16, 15, 8, 8, 4]
// [15, 42, 8, 23, 16, 4, 8]
// 7
// [ha, ha, ha]
Finished this page? Track your progress (saved only in your browser).