• Lessons Home
Topics
Community
  1. Lessons
  2. Apex Collections
  3. Sets
  4. Converting Between Collections

      Converting Between Collections

      Converting Between Collections

      Lists, sets, and maps each do one job well. Real code moves values between them, and Apex makes that a one line job because each collection can be built straight from another.

      From a List to a Set

      Passing a list into a set constructor copies every value in and drops the repeats:

      List<String> visits = new List<String>{ 'apex', 'soql', 'apex' };
      Set<String> unique = new Set<String>(visits);
      System.debug(unique.size()); // 2
      

      From a Set Back to a List

      A set has no positions and cannot be sorted, so convert it back to a list when you need order:

      List<String> uniqueList = new List<String>(unique);
      uniqueList.sort();
      System.debug(uniqueList[0]); // apex
      

      This round trip, list to set to list, is the standard way to get the distinct values of a list in a shape you can sort or index.

      From a Map to a List

      A map hands you both of its halves as ready made collections. values() is already a List, and keySet() returns a Set that the list constructor accepts:

      Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 12, 'paper' => 4 };
      List<String> itemNames = new List<String>(stock.keySet());
      List<Integer> counts = stock.values();
      

      Common Mistakes

      Every one of these conversions copies the values into a new collection. Changing the new one does not change the one you started from, so keep working with the result and not the original.

      Why This Matters

      Each shape unlocks different methods. Sets remove duplicates, lists sort and index, maps look values up by key. Converting between them means you never have to pick one shape and live with its limits.

      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