{"id":2376,"date":"2026-10-17T13:00:00","date_gmt":"2026-10-17T07:30:00","guid":{"rendered":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/"},"modified":"2026-11-15T11:30:16","modified_gmt":"2026-11-15T06:00:16","slug":"apex-comparable-comparator-sorting","status":"publish","type":"post","link":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/","title":{"rendered":"Sorting in Apex with Comparable and Comparator Explained"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Apex Comparable lets you decide how a list of your own objects should be sorted. By default, Apex can sort numbers and text, but it has no idea whether one course should come before another. You teach it by writing one method called compareTo.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This post builds on <a href=\"https:\/\/swapnilzambare.com\/blog\/apex-wrapper-inner-classes\/\">wrapper classes<\/a> and <a href=\"https:\/\/swapnilzambare.com\/blog\/apex-collections-list-set-map\/\">Apex collections<\/a>. We will sort course rows for Bright Path Tutors.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Apex Comparable?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">So Apex Comparable is an interface with a single method, <code>compareTo(Object o)<\/code>. Your class implements it and returns a negative number, zero, or a positive number. Then calling <code>sort()<\/code> on a List of that class uses your rule.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of a teacher arranging exam papers. The papers do not sort themselves. The teacher picks a rule, such as highest marks first, and arranges them by it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Apex Comparable Matters<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SOQL can sort with ORDER BY, but a wrapper list is built in Apex, so the database cannot help. Totals you calculate, rows you merge from two queries and lists you filter in memory all need sorting in code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Apex Comparable keeps that rule in one place. So the sort is consistent everywhere, and you do not repeat bubble-sort code across classes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How Apex Comparable Works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Apex compares items in pairs. For each pair it calls your method and reads the number you return. A negative result means the first item comes first.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-1.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-1-1024x640.png\" alt=\"Apex Comparable diagram showing how a custom sort works step by step\" class=\"wp-image-2374\" srcset=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-1-1024x640.png 1024w, https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-1-300x188.png 300w, https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-1-768x480.png 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">How a custom sort runs through compareTo.<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">The Return Value Rule<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This is the part most people get wrong, so keep it simple.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Return value<\/th><th>Meaning<\/th><\/tr><\/thead><tbody><tr><td>Negative number<\/td><td>This object comes before the other<\/td><\/tr><tr><td>Zero<\/td><td>Order between the two does not matter<\/td><\/tr><tr><td>Positive number<\/td><td>This object comes after the other<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Implementing Comparable<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class CourseRow implements Comparable {\n    public String name;\n    public Decimal fee;\n\n    public CourseRow(String name, Decimal fee) {\n        this.name = name;\n        this.fee = fee;\n    }\n\n    \/\/ Sort by fee, cheapest first\n    public Integer compareTo(Object o) {\n        CourseRow other = (CourseRow) o;\n        if (fee == other.fee) { return 0; }\n        return (fee &gt; other.fee) ? 1 : -1;\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Notice the cast on the first line. The parameter is <code>Object<\/code>, so you must convert it to your own type.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Running the Sort<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>List&lt;CourseRow&gt; rows = new List&lt;CourseRow&gt;{\n    new CourseRow('Python Basics', 10000),\n    new CourseRow('SQL Basics', 7000),\n    new CourseRow('Statistics', 12000)\n};\nrows.sort();\nfor (CourseRow r : rows) { System.debug(r.name + ' ' + r.fee); }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The log shows the cheapest course first.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SQL Basics 7000\nPython Basics 10000\nStatistics 12000<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Sorting Descending<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To reverse the order, flip the comparison rather than reversing the list afterwards.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public Integer compareTo(Object o) {\n    CourseRow other = (CourseRow) o;\n    if (fee == other.fee) { return 0; }\n    return (fee &gt; other.fee) ? -1 : 1;   \/\/ highest first\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Sorting by Two Fields<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Real lists often need a tie-breaker, such as fee first and then name.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public Integer compareTo(Object o) {\n    CourseRow other = (CourseRow) o;\n    if (fee != other.fee) {\n        return (fee &gt; other.fee) ? 1 : -1;\n    }\n    \/\/ Fees match, so fall back to the name\n    return name.compareTo(other.name);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>String.compareTo<\/code> already returns the right kind of number, so you can pass it straight through.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using a Comparator<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A comparator keeps the rule outside the class, so one list can be sorted several ways.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class FeeDescending implements Comparator&lt;CourseRow&gt; {\n    public Integer compare(CourseRow a, CourseRow b) {\n        if (a.fee == b.fee) { return 0; }\n        return (a.fee &gt; b.fee) ? -1 : 1;\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You then pass it to sort.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>rows.sort(new FeeDescending());<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Comparator also works on sObject lists, which Comparable cannot do because you do not own those classes.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>List&lt;Course__c&gt; courses = [SELECT Id, Name, Fee__c FROM Course__c LIMIT 50];\ncourses.sort(new CourseByFee());<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Comparable vs Comparator<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both decide order. This table shows when each fits.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Comparable<\/th><th>Comparator<\/th><\/tr><\/thead><tbody><tr><td>Rule lives<\/td><td>Inside the class<\/td><td>In its own class<\/td><\/tr><tr><td>Orders supported<\/td><td>One natural order<\/td><td>Many<\/td><\/tr><tr><td>Method name<\/td><td>compareTo<\/td><td>compare<\/td><\/tr><tr><td>Sorts sObjects<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Call<\/td><td>list.sort()<\/td><td>list.sort(comparator)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-2.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-2-1024x640.png\" alt=\"Apex Comparable compared with Comparator sorting in Salesforce\" class=\"wp-image-2375\" srcset=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-2-1024x640.png 1024w, https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-2-300x188.png 300w, https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-diagram-2-768x480.png 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">Comparable compared with Comparator in Apex.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">In short, use Comparable for the one obvious order. Add comparators when users can choose how to sort.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A Real Apex Comparable Example<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Bright Path shows a course table. Counsellors want to sort by fee, by name or by seats left, and the default should be cheapest first.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: Natural Order in the Class<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class CourseStat implements Comparable {\n    public String name;\n    public Decimal fee;\n    public Integer seatsLeft;\n\n    public CourseStat(String n, Decimal f, Integer s) {\n        name = n; fee = f; seatsLeft = s;\n    }\n    public Integer compareTo(Object o) {\n        CourseStat c = (CourseStat) o;\n        if (fee == c.fee) { return name.compareTo(c.name); }\n        return (fee &gt; c.fee) ? 1 : -1;\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Extra Orders as Comparators<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>public class BySeatsLeft implements Comparator&lt;CourseStat&gt; {\n    public Integer compare(CourseStat a, CourseStat b) {\n        return a.seatsLeft - b.seatsLeft;\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Subtraction is safe here because seat counts are small whole numbers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Try Both<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>List&lt;CourseStat&gt; list = new List&lt;CourseStat&gt;{\n    new CourseStat('Python Basics', 10000, 4),\n    new CourseStat('SQL Basics', 7000, 12),\n    new CourseStat('Statistics', 7000, 2)\n};\nlist.sort();\nSystem.debug('Default: ' + list[0].name);\nlist.sort(new BySeatsLeft());\nSystem.debug('Fewest seats: ' + list[0].name);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The log proves both rules work.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Default: SQL Basics\nFewest seats: Statistics<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">These are the sort options we built.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Order<\/th><th>Where it lives<\/th><th>First row<\/th><\/tr><\/thead><tbody><tr><td>Fee then name<\/td><td>compareTo<\/td><td>SQL Basics<\/td><\/tr><tr><td>Seats left<\/td><td>BySeatsLeft<\/td><td>Statistics<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes with Apex Comparable<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Forgetting to cast the Object parameter to your class.<\/li>\n\n<li>Returning true or false instead of a number.<\/li>\n\n<li>Subtracting large Decimals, which can lose precision when cast to Integer.<\/li>\n\n<li>Ignoring nulls, which throw a null pointer error during the sort.<\/li>\n\n<li>Writing your own loop to sort instead of using the built-in method.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Apex Comparable<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Handle nulls first and decide where they belong.<\/li>\n\n<li>Return 0 only when the items are truly equal.<\/li>\n\n<li>Use a tie-breaker field so the order is stable.<\/li>\n\n<li>Keep compareTo free of queries and DML.<\/li>\n\n<li>Use a comparator when the user picks the sort order.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Write a wrapper called StudentScore with name and marks. Sort it so the highest marks come first, and students with equal marks sort by name. Hint: use String.compareTo for the tie-breaker.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Most Asked Apex Comparable Interview Questions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Apex Comparable questions come up whenever an interviewer asks about sorting.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Apex Comparable Interview Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1: What is the Comparable interface in Apex?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Apex Comparable is an interface with one method, compareTo, that tells the sort how to order two objects of your class.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2: What does compareTo return?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It returns a negative number, zero or a positive number. Negative means this object comes first.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3: How do you sort a list after implementing it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Call sort() on the List, with no arguments. Then Apex uses your compareTo rule.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4: Why do you cast inside compareTo?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because the parameter type is Object. You cast it to your class before reading its fields.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5: Can you sort a list of sObjects with Comparable?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. You cannot change the standard classes, so use a Comparator or ORDER BY instead.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6: What is a Comparator in Apex?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is an interface with a compare method that lives outside the class. So one list can be sorted several ways.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7: How do you sort in descending order?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Flip the sign in your comparison, so the larger value returns a negative number.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8: Does List.sort work on plain text and numbers?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Those sort naturally with no extra code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Intermediate Apex Comparable Interview Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9: How do you sort by two fields?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Compare the first field, and when it is equal, return the comparison of the second field.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10: Why avoid subtracting Decimals in compareTo?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because casting the difference to Integer can round away a small gap, which makes items look equal.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q11: How do you handle null values?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Check for null first and decide whether nulls go to the top or the bottom, then return the matching number.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q12: Can compareTo contain a SOQL query?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It can, but it should not. Sorts run many comparisons, so a query there will hit limits quickly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q13: What is a stable sort?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One where equal items keep their original relative order. A tie-breaker field makes results predictable.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q14: When is ORDER BY better than a code sort?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Whenever the data comes straight from SOQL, because the database sorts faster and costs no CPU time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q15: Can a wrapper implement Comparable and another interface?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. A class can implement several interfaces at once.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q16: How do you sort a Map?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Maps have no order. So copy the keys to a List, sort that, then read the map in the sorted order.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Advanced Apex Comparable Interview Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q17: Scenario: users must sort a table by any column. How do you build it?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Write one comparator per column, store them in a Map by column name, and pass the chosen one into sort.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q18: How does sorting affect CPU limits?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each comparison runs your code, so a big list with heavy logic can hit the CPU limit. Keep compareTo tiny.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q19: Scenario: the sort throws a null pointer error. What is the likely cause?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A null field being compared. So guard every field before you compare it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q20: How would you sort by a related record&#8217;s field?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Pull the parent value into the wrapper when you build it, then compare that copied value.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q21: Why is returning a Boolean a common mistake?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because the method must return an Integer. A Boolean will not compile, and new developers often expect a yes or no.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q22: How do you test a custom sort?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Build a list in a known wrong order, sort it and assert on the first and last items.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q23: Can you sort inside a trigger?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Yes, but keep the list small. Large in-memory sorts in triggers add CPU time to every save.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q24: What is the advantage of comparators for a managed package?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Subscribers can pass their own comparator, so they change the order without editing your class.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q25: Does Apex Comparable work on a Set?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. Sets have no order, so you copy the values into a List first and sort that.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q26: How many comparisons does a sort make?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Roughly n times log n for a list of n items. So a 1,000-row list runs thousands of compareTo calls.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q27: Can you reuse one comparator across several classes?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Only if they share a type. Because Comparator is typed, you write one per class you sort.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q28: Scenario: the same list must sort differently on two screens. What do you do?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep the natural order in compareTo for the common case, then pass a comparator on the screen that needs the other order.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q29: Is Apex Comparable needed when you already use ORDER BY?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Not for straight query results. However, once you build or merge rows in Apex, the database order is lost, so you sort in code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/developer.salesforce.com\/docs\/atlas.en-us.apexref.meta\/apexref\/apex_interface_System_Comparable.htm\" target=\"_blank\" rel=\"noopener noreferrer\">Apex Reference: Comparable Interface<\/a><\/li>\n\n<li><a href=\"https:\/\/developer.salesforce.com\/docs\/atlas.en-us.apexref.meta\/apexref\/apex_interface_System_Comparator.htm\" target=\"_blank\" rel=\"noopener noreferrer\">Apex Reference: Comparator Interface<\/a><\/li>\n\n<li><a href=\"https:\/\/developer.salesforce.com\/docs\/atlas.en-us.apexcode.meta\/apexcode\/langCon_apex_collections_lists.htm\" target=\"_blank\" rel=\"noopener noreferrer\">Apex Developer Guide: Lists<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Apex Comparable adds a compareTo method so sort knows your rule.<\/li>\n\n<li>Negative, zero and positive decide the order.<\/li>\n\n<li>Cast the Object parameter to your own class first.<\/li>\n\n<li>Comparators live outside the class and can sort sObjects.<\/li>\n\n<li>Use ORDER BY when the data comes straight from SOQL.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we build our own loops with <a href=\"https:\/\/swapnilzambare.com\/blog\/apex-custom-iterator-iterable\/\">Custom Iterators and Iterable in Apex<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Apex Comparable lets you decide how a list of your own objects should be sorted. By default, Apex can sort numbers and text, but&hellip;<\/p>\n","protected":false},"author":1,"featured_media":2373,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[239,8,96],"tags":[98,26],"swapz_series":[],"class_list":["post-2376","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-apex-fundamentals","category-salesforce","category-salesforce-developer","tag-apex","tag-intermediate"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Apex Comparable and Comparator Sorting Guide<\/title>\n<meta name=\"description\" content=\"Learn Apex Comparable and Comparator to sort wrapper lists and sObjects by any field, with multi-field sorting and the most asked interview questions.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Apex Comparable and Comparator Sorting Guide\" \/>\n<meta property=\"og:description\" content=\"Learn Apex Comparable and Comparator to sort wrapper lists and sObjects by any field, with multi-field sorting and the most asked interview questions.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/\" \/>\n<meta property=\"og:site_name\" content=\"Swapnil Zambare - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-17T07:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-15T06:00:16+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Swapnil Zambare\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Swapnil Zambare\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/\"},\"author\":{\"name\":\"Swapnil Zambare\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#\\\/schema\\\/person\\\/10b09224c8bcc562716e86789427592a\"},\"headline\":\"Sorting in Apex with Comparable and Comparator Explained\",\"datePublished\":\"2026-10-17T07:30:00+00:00\",\"dateModified\":\"2026-11-15T06:00:16+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/\"},\"wordCount\":1560,\"publisher\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#organization\"},\"image\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/apex-comparable-comparator-sorting-featured.png\",\"keywords\":[\"Apex\",\"Intermediate\"],\"articleSection\":[\"Apex Fundamentals\",\"Salesforce\",\"Salesforce Developer\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/\",\"name\":\"Apex Comparable and Comparator Sorting Guide\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/apex-comparable-comparator-sorting-featured.png\",\"datePublished\":\"2026-10-17T07:30:00+00:00\",\"dateModified\":\"2026-11-15T06:00:16+00:00\",\"description\":\"Learn Apex Comparable and Comparator to sort wrapper lists and sObjects by any field, with multi-field sorting and the most asked interview questions.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/#primaryimage\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/apex-comparable-comparator-sorting-featured.png\",\"contentUrl\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/apex-comparable-comparator-sorting-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Apex Comparable featured image: code editor card with compareTo method\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/apex-comparable-comparator-sorting\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Sorting in Apex with Comparable and Comparator Explained\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/\",\"name\":\"Swapnil Zambare - Blog\",\"description\":\"Salesforce &amp; Tech Guides\",\"publisher\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#organization\",\"name\":\"Swapnil Zambare - Blog\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/site-icon-512.png\",\"contentUrl\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/09\\\/site-icon-512.png\",\"width\":512,\"height\":512,\"caption\":\"Swapnil Zambare - Blog\"},\"image\":{\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.linkedin.com\\\/in\\\/theSwapnilZambare\"]},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/#\\\/schema\\\/person\\\/10b09224c8bcc562716e86789427592a\",\"name\":\"Swapnil Zambare\",\"sameAs\":[\"https:\\\/\\\/swapnilzambare.com\\\/blog\"],\"url\":\"https:\\\/\\\/swapnilzambare.com\\\/blog\\\/author\\\/swapnil-zambare\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Apex Comparable and Comparator Sorting Guide","description":"Learn Apex Comparable and Comparator to sort wrapper lists and sObjects by any field, with multi-field sorting and the most asked interview questions.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/","og_locale":"en_US","og_type":"article","og_title":"Apex Comparable and Comparator Sorting Guide","og_description":"Learn Apex Comparable and Comparator to sort wrapper lists and sObjects by any field, with multi-field sorting and the most asked interview questions.","og_url":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/","og_site_name":"Swapnil Zambare - Blog","article_published_time":"2026-10-17T07:30:00+00:00","article_modified_time":"2026-11-15T06:00:16+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-featured.png","type":"image\/png"}],"author":"Swapnil Zambare","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Swapnil Zambare","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/#article","isPartOf":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/"},"author":{"name":"Swapnil Zambare","@id":"https:\/\/swapnilzambare.com\/blog\/#\/schema\/person\/10b09224c8bcc562716e86789427592a"},"headline":"Sorting in Apex with Comparable and Comparator Explained","datePublished":"2026-10-17T07:30:00+00:00","dateModified":"2026-11-15T06:00:16+00:00","mainEntityOfPage":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/"},"wordCount":1560,"publisher":{"@id":"https:\/\/swapnilzambare.com\/blog\/#organization"},"image":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/#primaryimage"},"thumbnailUrl":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-featured.png","keywords":["Apex","Intermediate"],"articleSection":["Apex Fundamentals","Salesforce","Salesforce Developer"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/","url":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/","name":"Apex Comparable and Comparator Sorting Guide","isPartOf":{"@id":"https:\/\/swapnilzambare.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/#primaryimage"},"image":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/#primaryimage"},"thumbnailUrl":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-featured.png","datePublished":"2026-10-17T07:30:00+00:00","dateModified":"2026-11-15T06:00:16+00:00","description":"Learn Apex Comparable and Comparator to sort wrapper lists and sObjects by any field, with multi-field sorting and the most asked interview questions.","breadcrumb":{"@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/#primaryimage","url":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-featured.png","contentUrl":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/11\/apex-comparable-comparator-sorting-featured.png","width":2400,"height":1260,"caption":"Apex Comparable featured image: code editor card with compareTo method"},{"@type":"BreadcrumbList","@id":"https:\/\/swapnilzambare.com\/blog\/apex-comparable-comparator-sorting\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/swapnilzambare.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Sorting in Apex with Comparable and Comparator Explained"}]},{"@type":"WebSite","@id":"https:\/\/swapnilzambare.com\/blog\/#website","url":"https:\/\/swapnilzambare.com\/blog\/","name":"Swapnil Zambare - Blog","description":"Salesforce &amp; Tech Guides","publisher":{"@id":"https:\/\/swapnilzambare.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/swapnilzambare.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/swapnilzambare.com\/blog\/#organization","name":"Swapnil Zambare - Blog","url":"https:\/\/swapnilzambare.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/swapnilzambare.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/09\/site-icon-512.png","contentUrl":"https:\/\/swapnilzambare.com\/blog\/wp-content\/uploads\/2026\/09\/site-icon-512.png","width":512,"height":512,"caption":"Swapnil Zambare - Blog"},"image":{"@id":"https:\/\/swapnilzambare.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.linkedin.com\/in\/theSwapnilZambare"]},{"@type":"Person","@id":"https:\/\/swapnilzambare.com\/blog\/#\/schema\/person\/10b09224c8bcc562716e86789427592a","name":"Swapnil Zambare","sameAs":["https:\/\/swapnilzambare.com\/blog"],"url":"https:\/\/swapnilzambare.com\/blog\/author\/swapnil-zambare\/"}]}},"_links":{"self":[{"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/posts\/2376","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/comments?post=2376"}],"version-history":[{"count":1,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/posts\/2376\/revisions"}],"predecessor-version":[{"id":3206,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/posts\/2376\/revisions\/3206"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/media\/2373"}],"wp:attachment":[{"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/media?parent=2376"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/categories?post=2376"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/tags?post=2376"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/swapnilzambare.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=2376"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}