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.
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.
Two Built-In Tools
Where They Live in the API
Arrays.sort: The Core Signatures
// 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
// 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:
// Sort strings by length (shortest first) Comparator<String> byLength = (a, b) -> a.length() - b.length(); Arrays.sort(words, byLength);
How to Apply Sorting
(a, b) → ... or use static helpers like Comparator.comparing().Example 1: Sorting Integers
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
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()
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
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.
Common Mistakes
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?