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]
List<Integer> scores = new List<Integer>{72, 45, 98, 60};— an unsorted list.scores.sort();—sort()rearrangesscoresitself — it doesn't return a new sorted list, it changes the original one directly ("in place").- (blank line)
System.debug(scores);— logs[45, 60, 72, 98]— after callingsort(), 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
List<String> names = new List<String>{'Carla', 'Amara', 'Ben'};— an unsorted list of strings.names.sort();—sort()works on anyListof a primitive comparable type —Integer,Decimal,String,Date, and a few others — using each type's natural ordering.- (blank line)
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]
List<Integer> scores = new List<Integer>{72, 45, 98, 60};— the starting list.scores.sort();— sorts ascending:[45, 60, 72, 98].scores.sort(System.SortOrder.DESCENDING);—sort()accepts an optionalSystem.SortOrderargument —DESCENDINGreverses the usual ascending order, without writing any custom comparison logic.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);
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.