• Lessons Home
Topics
Community
  1. Lessons
  2. Apex Collections
  3. Sets
  4. Set Operations

      Set Operations

      Set Operations

      Sets can be compared against each other. Three methods let you combine two sets, keep only what they share, or strip out what they have in common.

      Union with addAll()

      addAll() pours every value of one set into another. Duplicates disappear on their own, because a set never stores a value twice.

      Set<String> teamA = new Set<String>{ 'ana', 'ben' };
      Set<String> teamB = new Set<String>{ 'ben', 'cora' };
      teamA.addAll(teamB);
      System.debug(teamA.size()); // 3, ben was already there
      

      Intersection with retainAll()

      retainAll() keeps only the values that also live in the other set. Everything else is dropped.

      Set<String> mine = new Set<String>{ 'apex', 'soql', 'lwc' };
      Set<String> yours = new Set<String>{ 'soql', 'lwc', 'flow' };
      mine.retainAll(yours);
      System.debug(mine.size()); // 2, soql and lwc
      

      Difference with removeAll()

      removeAll() throws away every value that the other set also holds, leaving what is unique to the first set.

      Set<Integer> codes = new Set<Integer>{ 100, 200, 300 };
      codes.removeAll(new Set<Integer>{ 200 });
      System.debug(codes.size()); // 2
      

      Common Mistakes

      All three methods change the set they are called on and return a Boolean, not a new set. If you still need the original values, copy the set first:

      Set<String> shared = new Set<String>(mine);
      shared.retainAll(yours);
      

      Now shared holds the overlap and mine is untouched.

      Why This Matters

      Comparing two groups of ids is everyday work: which records did the query return that the input did not, which permissions does a user share with a profile, which emails appear in both files. These three methods answer those questions in one line.

      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