01 / 21

Arrays.sort &
Collections.sort

Master Java's built-in sorting methods. Learn how to sort primitive arrays, object collections, and write custom Comparators to control sort order.

Java

What Is Sorting?

Sorting rearranges elements into a defined order: ascending, descending, or any custom rule you specify. Java gives you two ready-made tools so you almost never need to write a sort algorithm by hand.

UNSORTED 5 1 8 3 sort() SORTED 1 3 5 8
Average time complexity: \( O(n \log n) \)

Two Built-In Tools

Arrays.sort()
Lives in java.util.Arrays. Works on arrays: int[], double[], String[], or any T[].
Collections.sort()
Lives in java.util.Collections. Works on Lists: ArrayList, LinkedList, or any List<T>.

Where They Live in the API

java.util Arrays sort(int[] a) sort(T[], Comparator) + binarySearch, fill, ... Collections sort(List<T>) sort(List, Comparator) + reverse, shuffle, ... int[], String[], T[] List<T> Comparator<T> (optional)

Arrays.sort: The Core Signatures

Java
// 1. Sort entire primitive array (ascending)
int[] nums = {5, 1, 8, 3};
Arrays.sort(nums);
// nums → [1, 3, 5, 8]

// 2. Sort a range [fromIndex, toIndex)
Arrays.sort(nums, 0, 2);
// sorts only index 0 and 1

// 3. Sort objects with a Comparator
String[] words = {"banana", "apple", "cherry"};
Arrays.sort(words, Comparator.reverseOrder());
// words → ["cherry", "banana", "apple"]

Collections.sort: The Core Signatures

Java
// 1. Sort a List (natural order)
List<Integer> list = new ArrayList<>(
    Arrays.asList(5, 1, 8, 3));
Collections.sort(list);
// list → [1, 3, 5, 8]

// 2. Sort with a Comparator
Collections.sort(list, Comparator.reverseOrder());
// list → [8, 5, 3, 1]

// 3. Modern alternative (Java 8+)
list.sort(Comparator.naturalOrder());
// same result as Collections.sort(list)

Comparable vs Comparator

Comparable<T> Comparator<T>
Interface java.lang.Comparable java.util.Comparator
Method compareTo(T o) compare(T a, T b)
Who defines it? The class itself An external object
Sort orders One (natural) Many (custom)
Modifies class? Yes No
Passed to sort? Implicitly Explicitly as 2nd arg

How a Comparator Works

A Comparator answers one question: given two elements a and b, which comes first? It returns an int:

Negative
a comes before b
Zero
a and b are equal
Positive
a comes after b
Java
// Sort strings by length (shortest first)
Comparator<String> byLength =
    (a, b) -> a.length() - b.length();

Arrays.sort(words, byLength);

How to Apply Sorting

1
Choose your data structure. Is it an array (int[], String[]) or a List (ArrayList)?
2
Pick the right method. Array → Arrays.sort(). List → Collections.sort() or list.sort().
3
Decide on ordering. Natural order (no Comparator needed) or custom order (pass a Comparator).
4
Write the Comparator (if needed). Lambda: (a, b) → ... or use static helpers like Comparator.comparing().
5
Call sort. The method sorts in-place: the original array/list is mutated.

Example 1: Sorting Integers

Java
import java.util.Arrays;

public class SortDemo {
  public static void main(String[] args) {
    int[] scores = {88, 42, 95, 67, 73};

    Arrays.sort(scores);

    System.out.println(
        Arrays.toString(scores));
    // Output: [42, 67, 73, 88, 95]
  }
}

Example 2: Custom Comparator

Java
import java.util.*;

public class LengthSort {
  public static void main(String[] args) {
    List<String> fruits = new ArrayList<>(
        Arrays.asList("banana", "fig",
            "strawberry", "kiwi"));

    // Sort by string length (shortest first)
    Collections.sort(fruits,
        (a, b) -> a.length() - b.length());

    System.out.println(fruits);
    // [fig, kiwi, banana, strawberry]
  }
}

Example 3: Comparator.comparing()

Java
import java.util.*;

record Student(String name, int grade) {}

public class StudentSort {
  public static void main(String[] args) {
    List<Student> roster = List.of(
        new Student("Ayla", 92),
        new Student("Ben", 87),
        new Student("Cara", 95));

    List<Student> sorted = new ArrayList<>(roster);

    // Sort by grade descending, then by name
    sorted.sort(
        Comparator.comparingInt(Student::grade)
            .reversed()
            .thenComparing(Student::name));

    sorted.forEach(System.out::println);
    // Student[name=Cara, grade=95]
    // Student[name=Ayla, grade=92]
    // Student[name=Ben, grade=87]
  }
}

Sort Flow Diagram

Call sort() Comparator provided? No Natural Order Yes Custom Order Sort Engine Primitives? Yes Dual-Pivot QS No TimSort

What Does Stable Mean?

A stable sort preserves the original order of elements that are considered equal by the comparison. This matters when sorting by multiple keys.

BEFORE (sort by grade): Ayla: 90 pos 0 Ben: 90 pos 1 Cara: 85 pos 2 STABLE SORT RESULT: Cara: 85 Ayla: 90 still before Ben Ben: 90 ✓ Order preserved

Common Mistakes

✕ Wrong method for type
Using Collections.sort() on an array or Arrays.sort() on a List. They don't mix: arrays need Arrays, lists need Collections.
✕ Primitives + Comparator
Passing a Comparator to Arrays.sort(int[]). Primitives don't support Comparators: use Integer[] instead.
✕ Integer overflow
Writing (a, b) → a - b for Integer.MIN_VALUE can overflow. Use Integer.compare(a, b) instead.

Summary Comparison

Arrays.sort() Collections.sort()
Input type Arrays (int[], T[]) List<T>
Package java.util.Arrays java.util.Collections
Algorithm (primitives) Dual-Pivot Quicksort N/A
Algorithm (objects) TimSort TimSort
Stable? Objects: Yes / Prims: No Yes
Comparator? Yes (objects only) Yes
Returns void (in-place) void (in-place)

Question 1 of 5

Which method would you use to sort an int[] array in ascending order?

Question 2 of 5

What sorting algorithm does Java use internally for Arrays.sort(String[])?

Question 3 of 5

Given the comparator (a, b) → b.length() - a.length(), how will strings be sorted?

Question 4 of 5

Why is (a, b) → a - b dangerous as a Comparator for Integers?

Question 5 of 5

Which chain of Comparator methods sorts students by grade descending, then by name ascending as a tiebreaker?