• Lessons Home
Topics
Community
  1. Lessons
  2. Apex Collections
  3. Lists
  4. Sorting Lists

      Sorting Lists

      Sorting Lists

      A list keeps its elements in the order you added them. When you want them in a meaningful order instead, Apex gives you a built-in sort() method that does the work for you.

      Calling sort()

      You call sort() on the list itself:

      List<Integer> nums = new List<Integer>{ 30, 10, 20 };
      nums.sort();
      // nums is now (10, 20, 30)
      

      Notice there is no = sign. The sort() method rearranges the elements inside the list you already have. It does not hand back a new list.

      What Order Do You Get

      For the built-in types you have seen so far, sort() uses the natural order:

      • Integer and Decimal sort from smallest to largest
      • String sorts alphabetically, with uppercase letters before lowercase ones
      • Date sorts from earliest to latest
      List<String> names = new List<String>{ 'Zoe', 'Ana', 'Miguel' };
      names.sort();
      // names is now (Ana, Miguel, Zoe)
      

      Common Mistakes

      The most common mistake is writing nums = nums.sort();. Because sort() hands back nothing, that line wipes out your list. Call sort() on its own line and keep using the same variable afterwards.

      Sorting an empty list is safe. There is nothing to rearrange, so the list simply stays empty.

      Why This Matters

      Sorted data is easier to read and easier to search. Ranking scores from lowest to highest, listing account names alphabetically, or putting dates in order all start with a single call to sort().

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In