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]
sort() rearranges scores itself — it doesn't return a new sorted list, it changes the original one directly ("in place"). After calling it, 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
sort() works on any List of a primitive comparable type — Integer, Decimal, String, Date, and a few others — using each type's natural ordering (numeric for numbers, alphabetical for strings).
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]
sort() accepts an optional System.SortOrder argument — DESCENDING reverses the usual ascending order, useful for something like "highest scores first" without writing any custom comparison logic.
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);
Sorting Lists Quiz
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.