• Lessons Home
Topics
Community
  1. Lessons
  2. Apex Collections
  3. Maps
  4. Map Keys and Values

      Map Keys and Values

      Map Keys and Values

      Once a map holds pairs you often need to walk through all of them. A map hands you its keys and its values as two separate collections you already know how to work with.

      keySet() Gives You the Keys

      keySet() returns a Set of every key in the map. Because keys are unique, a set is the natural shape for them.

      Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 12, 'paper' => 4 };
      Set<String> names = stock.keySet();
      System.debug(names.size()); // 2
      

      values() Gives You the Values

      values() returns a List of every value. Values may repeat, so a list is used instead of a set.

      List<Integer> counts = stock.values();
      System.debug(counts.size()); // 2
      

      Iterating a Map

      There is no way to loop over the pairs directly. The standard pattern is a for-each loop over keySet(), reading each value with get():

      Integer total = 0;
      for (String itemName : stock.keySet()) {
      	total = total + stock.get(itemName);
      }
      System.debug(total); // 16
      

      When you only care about the values, loop over values() instead and skip the lookups.

      Common Mistakes

      Do not add or remove pairs while looping over keySet(), because changing the map underneath the loop is not safe. Build up a separate collection inside the loop and apply your changes after it finishes.

      Why This Matters

      Summing amounts, finding the largest value, or collecting every key that passes a test are all the same shape of loop. Knowing that a map gives you a Set of keys and a List of values means every skill you learned for those collections works here too.

      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