• Lessons Home
Topics
Community
  1. Lessons
  2. Apex Collections
  3. Sets
  4. Introduction to Sets

      Introduction to Sets

      Introduction to Sets

      A list is great when order matters and repeats are fine. Sometimes you want the opposite: a bag of values where each value appears once and the order does not matter. That collection is a Set.

      Creating a Set

      You declare a set by naming the type it holds inside angle brackets:

      Set<String> tags = new Set<String>();
      tags.add('urgent');
      tags.add('review');
      // tags now holds urgent and review
      

      You can also fill a set at the moment you create it, or build one directly from a list:

      Set<Integer> codes = new Set<Integer>{ 100, 200, 300 };
      
      List<String> names = new List<String>{ 'Ana', 'Miguel' };
      Set<String> nameSet = new Set<String>(names);
      

      The Methods You Will Use Most

      • add(value) puts a value into the set
      • contains(value) hands back true if the value is already there
      • size() tells you how many values the set holds
      • remove(value) takes a value back out
      • isEmpty() tells you whether the set holds nothing at all
      Set<String> tags = new Set<String>{ 'urgent', 'review' };
      Boolean isUrgent = tags.contains('urgent'); // true
      Integer howMany = tags.size();              // 2
      

      No Index, No Order

      A set has no positions, so there is no tags.get(0). Asking a set for its first element is not a thing you can do. If you need to look at every value, use a for-each loop, and do not count on the order staying the same.

      Why This Matters

      contains() is the reason sets exist. Checking whether a value is already in a set is fast and reads clearly, which makes sets the right tool for membership questions like "have I already seen this record id".

      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