Collection algorithms and complexity
What you will learn
Collection algorithms are reusable operations such as searching, reversing, finding extrema and counting matches. Their preconditions matter: binary search needs sorted input, and operations that modify a list need suitable mutation support.
- Decode successful and unsuccessful binary search results.
- Use standard algorithms without violating input or mutability contracts.
- Choose linear scanning or sorting and searching based on workload.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed.
Find a value or its insertion position
import java.util.*;public class Main {
public static void main(String[] args) { List<Integer> sizes = List.of(10, 20, 40, 50); System.out.println(Collections.binarySearch(sizes, 40)); int missing = Collections.binarySearch(sizes, 30); System.out.println(missing); System.out.println(-(missing + 1)); int[] codes = {2, 5, 9}; System.out.println(Arrays.binarySearch(codes, 1)); }}Expected output:
2-32-1Thirty belongs before index 2, so the negative result is -3. One belongs at the first array position.
Rules and mental model
Collections.binarySearch(list,key) searches a list sorted by natural order; a comparator overload requires the same order used to sort. Arrays.binarySearch offers corresponding array overloads. A nonnegative result is a matching index; if no match exists, the negative result encodes the insertion position as -(position)-1. Recover the position as -(result + 1) only for a negative result. With duplicate keys, a matching index is not necessarily the first or last. An unsorted input gives no reliable result. For an array or random-access list, binary search uses logarithmically many probes, but a large sequential-access list can require linear link traversals. Linear scan needs no sorting and works well for a single lookup or a small unsorted collection. Sorting first has a cost, so it only pays off when ordering or repeated searches justify it; a map or set may be preferable for exact membership. No timing claims are made here.
Collections.min/max find extrema according to natural or supplied ordering; empty inputs have no extremum and these methods throw NoSuchElementException. Collections.frequency counts equality matches. Collections.reverse and swap change positions in a list; Collections.rotate moves elements by a signed distance. Collections.shuffle reorders a list randomly; a supplied Random seeded for a local fixture can support reproducible experiments, but avoid assuming a particular permutation across all implementations. These operations need list replacement support when they actually change elements. A fixed-size list can support replacement; an unmodifiable list does not. Copy before rearranging shared data. Collections.copy replaces existing slots of a destination list, not its capacity; it requires enough existing elements, not merely a large initial ArrayList capacity.
Search with the same descending comparator
import java.util.*;public class Main {
public static void main(String[] args) { List<Integer> ranks = new ArrayList<>(List.of(5, 20, 10)); Comparator<Integer> order = Comparator.reverseOrder(); ranks.sort(order); System.out.println(ranks); System.out.println(Collections.binarySearch(ranks, 10, order)); System.out.println(Collections.binarySearch(ranks, 15, order)); }}Expected output:
[20, 10, 5]1-2The position of 15 in descending order is 1. Searching with natural order instead would violate the precondition.
Summarize and rearrange a schedule
import java.util.*;public class Main {
public static void main(String[] args) { List<String> stops = new ArrayList<>(List.of("B", "A", "B", "C")); System.out.println(Collections.frequency(stops, "B")); System.out.println(Collections.min(stops)); System.out.println(Collections.max(stops)); Collections.swap(stops, 0, 1); Collections.reverse(stops); System.out.println(stops); Collections.rotate(stops, 1); System.out.println(stops); }}Expected output:
2AC[C, B, B, A][A, C, B, B]Frequency counts duplicates; extrema use natural string order. Swap, reverse and rotate alter positions, not membership.
Common mistakes
Do not treat every negative binary search result as -1, or use an absent result directly as an index. Also new ArrayList<>(100) has size zero; Collections.copy cannot copy into its unfilled slots.
Practice
Given sorted mutable list [10, 30, 50], search for 40. If absent, decode its insertion position and insert it. Print the result code and updated list.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Collection algorithms and complexity — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
binarySearch returns -4 for an absent key. What is its insertion position?
What must be true before binary searching with a comparator?
A sorted list contains two equal values. Which index must binarySearch return?
What happens when Collections.min receives an empty list?
Why is new ArrayList<>(100) not enough for Collections.copy from a list of size 3?