Course contentsShow
← Java
Lesson 1358 of 2,87030. Comparable and ComparatorFree lesson

Sorting Arrays with Arrays.sort()

Using Arrays.sort() with Comparators to sort arrays of objects in custom orders.

Sorting Arrays with Arrays.sort()

What you'll learn: How to sort arrays of objects in custom orders using Arrays.sort() with Comparator objects.

The Core Idea

While List.sort() handles collections, Arrays.sort() is your tool for sorting arrays of objects. Just like with lists, you can pass a Comparator to define custom sort orders. The method works in-place, modifying the original array directly.

Basic Syntax

Arrays.sort(array, comparator);

The first parameter is your array, and the second is a Comparator that defines how elements should be ordered.

Practical Example

Let's say you have an array of Person objects and want to sort by age:

Person[] people = {
    new Person("Alice", 30),
    new Person("Bob", 25),
    new Person("Charlie", 35)
};

// Sort by age
Arrays.sort(people, Comparator.comparingInt(Person::getAge));

// Now people is: Bob(25), Alice(30), Charlie(35)

Using Advanced Comparator Chains

You can leverage all the Comparator factory methods you've learned:

// Sort by age descending, then by name
Arrays.sort(people, 
    Comparator.comparingInt(Person::getAge)
              .reversed()
              .thenComparing(Person::getName));

Think of It Like This

If a List is a flexible container you can sort with .sort(), an array is a fixed container you sort with Arrays.sort(). Both accept the same Comparator strategies—only the syntax differs.

Key Takeaway: Use Arrays.sort(array, comparator) to sort arrays of objects with custom ordering logic, applying the same Comparator techniques you use for lists.