Beginner 20 min read

Sorting Lists

By the end of this lesson, you'll be able to:

  • Sort a List of primitives using the built-in sort() method
  • Explain that sort() changes the List in place rather than returning a new one
  • Reverse a sorted List to get descending order

Prerequisites: "Iterating Lists"

Sorting in place

List<Integer> scores = new List<Integer>{72, 45, 98, 60};
scores.sort();

System.debug(scores); // [45, 60, 72, 98]
  1. List<Integer> scores = new List<Integer>{72, 45, 98, 60}; — an unsorted list.
  2. scores.sort(); — sort() rearranges scores itself — it doesn't return a new sorted list, it changes the original one directly ("in place").
  3. (blank line)
  4. System.debug(scores); — logs [45, 60, 72, 98] — after calling sort(), the original unsorted order is gone.

Sorting works on Strings too

List<String> names = new List<String>{'Carla', 'Amara', 'Ben'};
names.sort();

System.debug(names); // ['Amara', 'Ben', 'Carla'] — alphabetical order
  1. List<String> names = new List<String>{'Carla', 'Amara', 'Ben'}; — an unsorted list of strings.
  2. names.sort(); — sort() works on any List of a primitive comparable type — Integer, Decimal, String, Date, and a few others — using each type's natural ordering.
  3. (blank line)
  4. System.debug(names); — logs ['Amara', 'Ben', 'Carla'] — alphabetical order.

Getting descending order

List<Integer> scores = new List<Integer>{72, 45, 98, 60};
scores.sort(); // ascending: [45, 60, 72, 98]
scores.sort(System.SortOrder.DESCENDING);
System.debug(scores); // [98, 72, 60, 45]
  1. List<Integer> scores = new List<Integer>{72, 45, 98, 60}; — the starting list.
  2. scores.sort(); — sorts ascending: [45, 60, 72, 98].
  3. scores.sort(System.SortOrder.DESCENDING); — sort() accepts an optional System.SortOrder argument — DESCENDING reverses the usual ascending order, without writing any custom comparison logic.
  4. System.debug(scores); — logs [98, 72, 60, 45] — highest scores first.

Exercise

Given List<Decimal> prices = new List<Decimal>{45.5, 12.0, 89.99, 3.25}, sort it in descending order and debug the result.

Show hint

prices.sort(System.SortOrder.DESCENDING);

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

Sorting Lists Quiz

1. What does calling sort() on a List do?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Apex Lists of primitive types have a built-in sort() method — a single call replaces writing a sorting algorithm by hand.