ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Algorithms
Book 1 · Volume II — Generics, Collections & Type System · Topic 6.4

Algorithms

Sorting, searching and Collections utility methods

12 min readStage 1 · Foundations14 interview questions
Prerequisites
5.3 Tree-Based Collections (Comparator)
Covers
Sorting · Searching · Collections utility methods
Related
7.1 Immutable Collections · B1V3 Streams (sorted, collectors)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

The JDK provides tested, optimised implementations of the algorithms most programs need: sorting (List.sort, Collections.sort, Arrays.sort), searching (Collections.binarySearch, Arrays.binarySearch), and a library of utility operations in java.util.Collections — reordering, extremes, frequency, wrappers and factory methods. Using them avoids subtle bugs of hand-written versions.

2Why It Exists

Sorting and searching look easy and are easy to get subtly wrong. The best-known example is binary search: in 2006 Joshua Bloch showed that the JDK's own Arrays.binarySearch, like the textbook version it followed, computed the midpoint as (low + high) / 2, which overflows once an array has more than about a billion elements. The library was fixed to use (low + high) >>> 1; code that copied the textbook still has the bug. Hand-written sorts have similar traps: instability, quadratic worst cases and recursion depth.

The JDK's algorithms are tested on every platform, tuned for real data and maintained by people who study the problem. Java 7 replaced the object merge sort with TimSort, which is much faster on the partly sorted data that business systems produce, and the primitive quicksort with dual-pivot quicksort; JDK 14 improved that again. A program that calls List.sort or Collections.binarySearch gets those improvements with every JDK upgrade, without changing a line.

3Core Concepts

Sorting

Object sorts (List.sort, Collections.sort, Arrays.sort(Object[])) use TimSort, a hybrid of merge sort and insertion sort: O(n log n) worst case, close to O(n) on partially sorted data, and stable — equal elements keep their relative order, which makes multi-key sorting by successive sorts possible. Primitive arrays use dual-pivot quicksort, which is faster but not stable (stability is meaningless for primitives). Arrays.parallelSort uses fork/join for large arrays. Since Java 8, List.sort sorts in place, and ArrayList does it directly on its array.

TimSort's strategy
Figure 1 — TimSort's strategy

Searching

Collections.binarySearch(list, key[, comparator]) and Arrays.binarySearch find an element in O(log n) — but only if the data is sorted by the same ordering; otherwise the result is undefined. If the key is absent they return -(insertionPoint) - 1, which tells you where to insert to keep order. For unsorted data, indexOf, contains and streams perform O(n) linear searches; for repeated lookups, a HashSet or TreeSet is usually better than repeated searching.

Binary search halves the search range at each step
Figure 2 — Binary search halves the search range at each step

Collections utility methods

java.util.Collections contains static helpers grouped into algorithms (sort, shuffle, reverse, rotate, swap, fill, copy, min, max, frequency, disjoint, nCopies), wrappers (unmodifiableList, synchronizedMap, checkedList) and factories (emptyList, singletonList, emptyMap). Many are now complemented by List/Map factory methods (7.1) and streams, but they remain common in existing code and interviews.

Frequently used Collections utilities
Figure 3 — Frequently used Collections utilities

4How It Works Internally

list.sort(cmp) is where every sort starts; Collections.sort(list, cmp) simply calls it. What happens next depends on the list (Figure 4). ArrayList overrides sort and sorts its internal array in place. The default method in List copies the elements into an array, sorts the array and writes the result back through a ListIterator. Immutable lists throw UnsupportedOperationException without looking at the elements.

list.sort() sorts in place, through a copy, or not at all
Figure 4 — list.sort() sorts in place, through a copy, or not at all

TimSort, used for object arrays, first looks for runs: stretches that are already ascending, or strictly descending, which it reverses in place. Runs shorter than a minimum length, between 16 and 32 elements depending on the array size, are extended with binary insertion sort, and arrays of fewer than 32 elements are sorted by binary insertion sort alone. Runs are pushed on a stack and merged while the stack keeps a balance invariant; during a merge, when one run keeps winning, TimSort switches to galloping, an exponential search that copies long blocks at once. Already sorted data is one run and costs n - 1 comparisons. The merge code also checks that the comparator behaves consistently, which is where "Comparison method violates its general contract!" comes from (Figure 5).

Equality within a tolerance is not transitive, and TimSort can detect it
Figure 5 — Equality within a tolerance is not transitive, and TimSort can detect it

Collections.binarySearch uses index access when the list implements RandomAccess or has fewer than 5,000 elements, and an iterator-based search otherwise, so a large LinkedList still needs only O(log n) comparisons but O(n) link traversals. Arrays.parallelSort sorts arrays of fewer than 8,192 elements sequentially; larger ones are split into pieces sorted in parallel on the common ForkJoinPool and merged.

5APIs / Features / Syntax

The algorithms are spread over List, Arrays, Collections and Comparator. The ones used most, with their cost:

MethodCostNotes
list.sort(cmp), Collections.sort(list)O(n log n)Stable; null cmp = natural order
Arrays.sort(Object[]) / Arrays.sort(int[])O(n log n)TimSort (stable) / dual-pivot quicksort
Arrays.parallelSort(array)O(n log n) / coresSequential below 8,192 elements
Collections.binarySearch(list, key[, cmp])O(log n)List sorted by the same order; -(ins) - 1 if absent
Collections.min / max (coll[, cmp])O(n)NoSuchElementException on an empty collection
Collections.frequency, disjointO(n), O(n x m)disjoint is fast when one is a Set
Collections.reverse, shuffle, rotate, swapO(n)Need a modifiable list
Comparator.comparing(...).thenComparing(...)-reversed(), nullsFirst(), nullsLast()
List.reversed() (SequencedCollection)O(1)Java 21: a reversed view, not a copy

Comparator.comparing with a key extractor and Integer.compare, Long.compare or Double.compare should replace hand-written comparison logic. For streams, sorted(cmp) sorts a copy and leaves the source alone, and Collectors.toCollection(TreeSet::new) keeps elements sorted as they arrive.

6Practical Examples

Example 1 — Sorting, searching and utilities

Problem. A reporting module sorts orders by customer and then by total, highest first, keeps a list of thresholds sorted while adding values, and uses a handful of Collections and Arrays utilities.

JAVASorting, searching and utilities
// Multi-key sort with comparators (stable)
orders.sort(Comparator.comparing(Order::customer)
                      .thenComparing(Order::total, Comparator.reverseOrder()));

// Binary search with insertion point
List<Integer> sorted = new ArrayList<>(List.of(3, 8, 12, 17, 21));
int pos = Collections.binarySearch(sorted, 15);  // -4 → insertion point 3
if (pos < 0) sorted.add(-pos - 1, 15);  // keeps the list sorted

// Utilities
int maxQty = Collections.max(quantities);
int dupes = Collections.frequency(emails, "a@x.com");
boolean noOverlap = Collections.disjoint(admins, suspended);
Collections.shuffle(deck, new Random(42));               // reproducible shuffle
List<String> placeholders = Collections.nCopies(5, "?");

// Primitive arrays
int[] ids = loadIds();
Arrays.sort(ids);                                        // dual-pivot quicksort
int idx = Arrays.binarySearch(ids, 1042);
Arrays.parallelSort(bigArray);  // fork/join for large arrays

Why it works. thenComparing(Order::total, Comparator.reverseOrder()) reverses only the second key, so customers stay in ascending order. 15 is not in the list, so binarySearch returns -4, and -pos - 1 gives the insertion point 3 that keeps the list sorted. shuffle with a seeded Random gives the same order on every run, which makes tests repeatable; nCopies returns an immutable list that stores the element once.

Example 2 — Mini program: a leaderboard from JDK algorithms only

Problem. A game service ranks players by points, highest first, with ties broken by name. It also shows the ranking grouped by team, inserts a late score without re-sorting, and reports a few statistics.

JAVALeaderboard.java
public class Leaderboard {
    record Score(String player, String team, int points) {}
 
    static final Comparator<Score> RANKING =        // points desc, then name
            Comparator.comparingInt(Score::points).reversed()
                      .thenComparing(Score::player);
 
    static List<String> names(List<Score> s) {
        return s.stream().map(Score::player).toList();
    }
 
    public static void main(String[] args) {
        List<Score> board = new ArrayList<>(List.of(
                new Score("mira", "red", 70), new Score("arjun", "blue", 90),
                new Score("li", "red", 70), new Score("sam", "blue", 55),
                new Score("eva", "green", 90)));
 
        board.sort(RANKING);                               // 1. multi-key sort
        System.out.println("ranking: " + names(board));
 
        List<Score> byTeam = new ArrayList<>(board);       // 2. stable re-sort:
        byTeam.sort(Comparator.comparing(Score::team));    //    ranks kept
        System.out.println("by team: " + byTeam.stream()
                .map(s -> s.team() + ":" + s.player()).toList());
 
        Score late = new Score("noor", "green", 75);       // 3. sorted insert
        int pos = Collections.binarySearch(board, late, RANKING);
        int at = pos < 0 ? -pos - 1 : pos;
        board.add(at, late);
        System.out.println("noor inserted at " + at + ": " + names(board));
 
        List<Integer> points = board.stream().map(Score::points).toList();
        System.out.println("top " + Collections.max(points)  // 4. utilities
                + ", scores of 90: " + Collections.frequency(points, 90)
                + ", top 3: " + names(board.subList(0, 3)));
    }
}
OUTPUT
ranking: [arjun, eva, li, mira, sam]
by team: [blue:arjun, blue:sam, green:eva, red:li, red:mira]
noor inserted at 2: [arjun, eva, noor, li, mira, sam]
top 90, scores of 90: 2, top 3: [arjun, eva, noor]

Why it behaves this way. RANKING puts arjun before eva because they tie on 90 points and the second key is the name. Sorting that ranking by team alone keeps the ranking inside each team, because TimSort is stable: arjun stays ahead of sam, li ahead of mira. binarySearch with the same comparator finds no score of 75 and returns -3, so noor goes in at index 2 with one O(n) insert instead of a new O(n log n) sort. subList(0, 3) is a view, so the top three cost nothing to extract.

Example 3 — Two comparators that break the contract

Problem. Section 8 says that "Comparison method violates its general contract!" in production almost always comes from a bad comparator. The program shows the two most common ones: equality within a tolerance, and subtraction.

JAVABrokenComparators.java
public class BrokenComparators {
    public static void main(String[] args) {
        // 1. "nearly equal" prices: equality that is not transitive
        Comparator<Double> nearly = (a, b) ->
                Math.abs(a - b) < 0.5 ? 0 : Double.compare(a, b);
        Random rnd = new Random(7);
        List<Double> prices = new ArrayList<>();
        for (int i = 0; i < 200; i++) prices.add(rnd.nextInt(1000) / 100.0);
        try {
            new ArrayList<>(prices).sort(nearly);
            System.out.println("1. sorted");
        } catch (IllegalArgumentException e) {
            System.out.println("1. " + e.getMessage());
        }
        List<Double> ok = new ArrayList<>(prices);
        ok.sort(Comparator.naturalOrder());
        System.out.println("   fixed: " + ok.subList(0, 3) + " ...");
 
        // 2. subtraction overflows for large values
        List<Integer> balances = new ArrayList<>(
                List.of(2_000_000_000, -2_000_000_000, 0, 5));
        balances.sort((a, b) -> a - b);
        System.out.println("2. a - b:            " + balances);
        balances.sort(Integer::compare);
        System.out.println("   Integer::compare: " + balances);
    }
}
OUTPUT
1. Comparison method violates its general contract!
   fixed: [0.04, 0.12, 0.12] ...
2. a - b:            [2000000000, -2000000000, 0, 5]
   Integer::compare: [-2000000000, 0, 5, 2000000000]

Why it behaves this way. The tolerance comparator calls 1.00 and 1.40 equal, and 1.40 and 1.80 equal, but not 1.00 and 1.80 (Figure 5). On these 200 prices TimSort's merge detects the inconsistency and throws; with other data, or fewer than 32 elements, the same comparator may silently produce a wrong order, which is why it passes tests. The subtraction comparator overflows: 2_000_000_000 - (-2_000_000_000) exceeds Integer.MAX_VALUE and wraps to a negative number, so the largest balance is sorted first. Integer.compare and Double.compare never overflow; rounding belongs in the data, not in the comparator.

Example 4 — Searching with the wrong order, and copying into a short list

Problem. SKU codes are sorted case-insensitively for display, and another part of the code looks them up with binarySearch. A third part tries to copy the sorted list into an existing list.

JAVASearchPitfalls.java
public class SearchPitfalls {
    public static void main(String[] args) {
        Comparator<String> ci = String.CASE_INSENSITIVE_ORDER;
        List<String> skus = new ArrayList<>(
                List.of("D-13", "a-10", "e-14", "B-11", "c-12"));
        skus.sort(ci);
        System.out.println("sorted ignoring case: " + skus);
        System.out.println("search D-13, natural order:   "
                + Collections.binarySearch(skus, "D-13"));
        System.out.println("search D-13, same comparator: "
                + Collections.binarySearch(skus, "D-13", ci));
 
        List<String> target = new ArrayList<>(List.of("x"));
        try {
            Collections.copy(target, skus);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("copy into a shorter list: " + e.getMessage());
        }
        List<String> copy = new ArrayList<>(skus);           // what was meant
        Collections.reverse(copy);
        Collections.rotate(copy, 1);
        System.out.println("reversed, then rotated by 1: " + copy);
    }
}
OUTPUT
sorted ignoring case: [a-10, B-11, c-12, D-13, e-14]
search D-13, natural order:   -1
search D-13, same comparator: 3
copy into a shorter list: Source does not fit in dest
reversed, then rotated by 1: [a-10, e-14, D-13, c-12, B-11]

Why it behaves this way. In natural order every upper-case letter comes before every lower-case one, so the search compares "D-13" with "c-12", decides it must be to the left and never finds it: the result -1 claims the key belongs at the start. With the comparator used for sorting, it is found at index 3. Collections.copy overwrites the first elements of an existing list and never grows it, so a destination with one element cannot take five; new ArrayList<>(source) is what such code usually means.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
binarySearch on an unsorted list, or with a different comparator than the sortUndefined result: usually a negative "not found" for a key that is present (Example 4)Search with the comparator used for sorting
Comparators violating the contract (inconsistent or intransitive)TimSort may throw IllegalArgumentException: Comparison method violates its general contract! - or silently mis-sort (Example 3)Build comparators from Comparator.comparing and Integer/Double.compare
Comparing by subtraction: (a, b) -> a - bOverflow for large or negative values gives a wrong orderInteger.compare(a, b) or Comparator.comparingInt
Sorting an immutable list (List.of, toList()) in placeUnsupportedOperationException, even if it is already sortedstream().sorted().toList(), or sort a new ArrayList<>(list)
Collections.copy expecting to grow the destinationIndexOutOfBoundsException: "Source does not fit in dest"new ArrayList<>(source), or addAll
Using Collections.synchronizedList and assuming iteration is thread-safeEach call is synchronised, the traversal is not: CME or inconsistent readsHold the list's lock while iterating, or use a concurrent collection
Sorting a whole list to take the top NO(n log n) time and a full copy when N is smallA PriorityQueue of size N: O(n log N) (Q12)

8Performance & Production Considerations

Sorting is O(n log n) and allocates up to n/2 temporary space for TimSort; sorting millions of objects in a request path can dominate latency. Sort once and maintain order (TreeMap, insertion into sorted positions) if data is queried repeatedly, or push sorting to the database with an index. The "Comparison method violates its general contract" error in production almost always points to a comparator using mutable data, subtraction, or inconsistent null handling.

9Architecture & Design Considerations

Decide where ordering and searching belong: small in-memory collections sorted in the service; large or shared datasets sorted and searched in the database, search engine or index where they live. Algorithms that are correct in memory can become bottlenecks when data grows by orders of magnitude — a classic cause of services slowing down as customers grow.

10Interview Questions & Answers

Q1L1 · BasicConcept

Which algorithm does Collections.sort use?

TimSort, a stable hybrid of merge sort and insertion sort, O(n log n) worst case and very fast on partially sorted data.

Q2L2 · IntermediateConcept

What is a stable sort and why does it matter?

Equal elements keep their original relative order. It allows sorting by one key after another and preserves a meaningful existing order for ties.

Q3L2 · IntermediateConcept

What does Collections.binarySearch return if the key is not found?

A negative value, -(insertion point) - 1, where the insertion point is the index at which the key would be inserted to keep the list sorted.

Q4L3 · Senior EngineerInternals

Why does Arrays.sort use a different algorithm for int[] than for Object[]?

Primitives have no identity, so stability is irrelevant; dual-pivot quicksort is faster and needs no extra memory. Objects need a stable sort because equal objects can be distinguishable, so TimSort is used.

Q5L3 · Senior EngineerTricky

What causes "Comparison method violates its general contract!" and how do you fix it?

A comparator that is not a consistent total order: using subtraction with overflow, comparing mutable fields that change during sorting, mishandling nulls or NaN, or non-transitive logic. Rewrite it with Comparator.comparing, Integer.compare and explicit nullsFirst/nullsLast.

Q6L4 · Technical ArchitectScenario

A report endpoint sorts and searches large lists in memory and has become slow as data grew. What options would you consider?

Move sorting, filtering and pagination to the database with appropriate indexes; keep pre-sorted structures (TreeMap) if data is in memory and queried often; limit result sizes; and cache computed reports. In-memory sorting of the full dataset on every request does not scale.

Q7L1 · BasicCode

What does this program print?

JAVABinarySearchQuiz.java
public class BinarySearchQuiz {
    public static void main(String[] args) {
        List<Integer> xs = List.of(10, 20, 30, 40);
        System.out.println(Collections.binarySearch(xs, 30) + " "
                + Collections.binarySearch(xs, 5) + " "
                + Collections.binarySearch(xs, 35) + " "
                + Collections.binarySearch(xs, 99));
    }
}

It prints 2 -1 -4 -5. 30 is found at index 2. A missing key returns -(insertion point) - 1: 5 would go at index 0, so -1; 35 at index 3, so -4; 99 at the end, index 4, so -5. The "minus one" guarantees that a missing key never returns 0, which would be confused with "found at index 0".

Q8L2 · IntermediateCode

What does this program print?

JAVAStableQuiz.java
public class StableQuiz {
    record Emp(String name, String dept) {}
 
    public static void main(String[] args) {
        List<Emp> staff = new ArrayList<>(List.of(new Emp("zoe", "ops"),
                new Emp("amit", "dev"), new Emp("kim", "ops"),
                new Emp("bo", "dev")));
        staff.sort(Comparator.comparing(Emp::name));
        staff.sort(Comparator.comparing(Emp::dept));
        System.out.println(staff.stream().map(Emp::name).toList());
    }
}

It prints [amit, bo, kim, zoe]. The first sort orders by name; the second sorts by department only, and because List.sort is stable, people in the same department keep their name order: amit before bo in dev, kim before zoe in ops. The same result in one sort is Comparator.comparing(Emp::dept).thenComparing(Emp::name), which is clearer and sorts once.

Q9L3 · Senior EngineerCode

What does this program print?

JAVAOverflowQuiz.java
public class OverflowQuiz {
    public static void main(String[] args) {
        Integer[] xs = {Integer.MAX_VALUE, -2, 0};
        Arrays.sort(xs, (a, b) -> a - b);
        System.out.println(Arrays.toString(xs));
    }
}

It prints [2147483647, -2, 0]: the array is not sorted at all. -2 - Integer.MAX_VALUE overflows to a large positive number, so the comparator claims that -2 is greater than MAX_VALUE, and 0 - (-2) is positive too. TimSort therefore sees one ascending run covering the whole array and returns at once. Integer::compare sorts it correctly to [-2, 0, 2147483647].

Q10L3 · Senior EngineerTricky

Why does List.of(3, 1, 2).sort(null) throw, while Arrays.asList(3, 1, 2).sort(null) works?

List.of returns an immutable list, and its sort throws UnsupportedOperationException before looking at the elements, even if they are already in order. Arrays.asList returns a fixed-size list backed by the array: it cannot grow or shrink, but set is allowed, so the default sort can write the sorted elements back, and the array behind it is sorted too. stream().sorted().toList() gives a sorted immutable copy of either.

Q11L3 · Senior EngineerInternals

How does TimSort get close to O(n) on nearly sorted data?

It begins by finding runs that are already in order, reversing strictly descending ones, and extends short runs to a minimum length with binary insertion sort. A fully sorted array is a single run and needs n - 1 comparisons. Runs are merged pairwise from a stack that keeps their lengths balanced, and galloping mode copies long blocks when one run keeps winning, so data made of a few sorted pieces, such as appended batches or a sorted list with a few changes, needs far fewer than n log n comparisons.

Q12L4 · Technical ArchitectDesign

Design the "top 10 products by revenue" calculation over 50 million sale records processed in one service.

Do not sort 50 million records to keep 10. Aggregate revenue per product first, for example in a HashMap<String, Long>, then keep a PriorityQueue of size 10 ordered by revenue ascending: offer each product and poll the smallest when the queue exceeds 10, which is O(n log 10) time and O(10) extra space. Sort the ten survivors at the end. If the records live in a database, GROUP BY with ORDER BY ... LIMIT 10 on an index moves the whole computation to where the data is.

Q13L5 · Solution ArchitectTrade-off

Data queried in sorted order is updated all day. Do you keep it in a TreeMap, keep a sorted ArrayList with binary-search inserts, or sort on every read?

A TreeMap gives O(log n) inserts, deletes and range queries, at the cost of a node per entry and poorer cache locality. A sorted ArrayList with binarySearch inserts reads very fast and compactly, but each insert shifts O(n) elements, so it suits read-heavy data with few writes (Example 2). Sorting on read is simplest when reads are rare or the data is small. Under concurrency, ConcurrentSkipListMap or immutable sorted snapshots replace both. Choose from the measured read/write ratio and data size, and push large sorted queries to an indexed store.

Q14L5 · Solution ArchitectScenario

After a legacy batch system moves from Java 6 to a current JDK, a nightly job fails with "Comparison method violates its general contract!". It ran for years without errors. What do you do?

The comparator was always broken: the merge sort used before Java 7 did not detect inconsistent comparisons and silently produced an order, while TimSort checks and throws. Look for subtraction, tolerance or mutable keys, and inconsistent null handling in the comparator, and fix it with Comparator.comparing and the compare methods. The system property java.util.Arrays.useLegacyMergeSort=true restores the old algorithm only as a short-term stopgap, and it may be removed in a future JDK. Also check the old reports: their order was never guaranteed.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Object sorts: TimSort, stable, O(n log n); primitive sorts: dual-pivot quicksort.
  • binarySearch requires data sorted by the same ordering; negative result encodes the insertion point.
  • Collections offers reordering, extremes, frequency, wrappers and factories.
  • Comparators must be consistent total orders.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.