Java
ArrayList
Sorting
Programming
Code Example

How to sort an ArrayList in Java

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Sorting an ArrayList in Java is usually straightforward because the Collections API already provides the needed operations. The real choice is whether your elements have a natural order or whether you need to supply a custom Comparator.

Modern Java code most often uses List.sort, but Collections.sort is still common and works the same way conceptually. Both mutate the list in place.

Sorting Values with Natural Ordering

If the elements already know how to compare themselves, sorting is simple. Types such as Integer, String, and LocalDate already implement Comparable.

java
1import java.util.ArrayList;
2import java.util.List;
3
4public class Main {
5    public static void main(String[] args) {
6        List<Integer> numbers = new ArrayList<>();
7        numbers.add(42);
8        numbers.add(7);
9        numbers.add(19);
10        numbers.add(7);
11
12        numbers.sort(null);
13        System.out.println(numbers);
14    }
15}
text
[7, 7, 19, 42]

Passing null to sort means "use natural ordering." The older equivalent is Collections.sort(numbers).

Duplicates are not a problem. They remain in the list, and Java's sort is stable, so elements that compare equal keep their relative order.

Sorting Objects with a Comparator

When you store custom objects, Java needs to know what "sorted" means. You can encode that rule with a Comparator.

java
1import java.util.ArrayList;
2import java.util.Comparator;
3import java.util.List;
4
5class Person {
6    final String name;
7    final int age;
8
9    Person(String name, int age) {
10        this.name = name;
11        this.age = age;
12    }
13
14    @Override
15    public String toString() {
16        return name + ":" + age;
17    }
18}
19
20public class Main {
21    public static void main(String[] args) {
22        List<Person> people = new ArrayList<>();
23        people.add(new Person("Mina", 31));
24        people.add(new Person("Alex", 24));
25        people.add(new Person("Sara", 24));
26
27        people.sort(Comparator.comparingInt(person -> person.age)
28                              .thenComparing(person -> person.name));
29
30        System.out.println(people);
31    }
32}
text
[Alex:24, Sara:24, Mina:31]

This is often better than making the class implement Comparable when the ordering rule is specific to one use case.

Collections.sort Versus List.sort

Both approaches sort the same way. The practical difference is style:

  • 'Collections.sort(list) is older and still perfectly valid'
  • 'list.sort(comparator) is shorter and fits naturally with lambda expressions'

For new code, many developers prefer list.sort(...) because it keeps the action on the list itself. But there is no major algorithmic difference between the two.

Sorting Without Changing the Original List

Because sorting mutates the list, copy the data first if the original order matters:

java
1List<Integer> original = List.of(5, 2, 8, 1);
2List<Integer> sorted = new ArrayList<>(original);
3sorted.sort(null);
4
5System.out.println(original);
6System.out.println(sorted);

This small step is useful in tests, UI code, and anywhere the same collection must be viewed in more than one order.

Descending Order and Null Handling

Descending order is easy with comparator helpers:

java
numbers.sort(Comparator.reverseOrder());

If your list may contain null, handle that explicitly:

java
people.sort(Comparator.nullsLast(
        Comparator.comparing(person -> person.name)));

Without a null-aware comparator, sorting a list that contains null may throw a NullPointerException.

Case-insensitive sorting is another common variant:

java
List<String> names = new ArrayList<>(List.of("bob", "Alice", "carol"));
names.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println(names);

That pattern is useful when display order should feel natural to users rather than following raw Unicode code-point order.

Common Pitfalls

  • Forgetting that sorting changes the original ArrayList in place.
  • Trying to sort custom objects without either Comparable or a Comparator.
  • Assuming duplicates are removed. Sorting changes order, not membership.
  • Ignoring null values when the list can contain them.

Summary

  • Use list.sort(null) or Collections.sort(list) for values with natural ordering.
  • Use a Comparator for custom sort logic.
  • 'List.sort and Collections.sort are similar in behavior; List.sort is often cleaner in modern Java.'
  • Sorting is in place, so it mutates the original list.
  • Handle duplicates and null values intentionally when designing your comparator.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms