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

      Introduction to Maps

      Introduction to Maps

      A Map stores pairs. Each pair has a key you look things up by and a value you get back. Where a list answers what is at position 2, a map answers what is the price of apex-guide.

      Declaring a Map

      A map declaration names two types: the key type first, then the value type.

      Map<String, Integer> prices = new Map<String, Integer>();
      

      You can also fill a map as you create it, using => between each key and value:

      Map<String, Integer> stock = new Map<String, Integer>{ 'pens' => 12, 'paper' => 4 };
      

      Adding and Reading Pairs

      put() stores a pair and get() reads the value back:

      prices.put('guide', 25);
      Integer guidePrice = prices.get('guide'); // 25
      

      Putting the same key twice does not create a second pair. The new value replaces the old one, so size() stays the same.

      Missing Keys

      get() returns null when the key was never stored. Ask containsKey() first when a missing key needs different handling:

      if (prices.containsKey('poster')) {
      	Integer posterPrice = prices.get('poster');
      }
      

      Common Mistakes

      Do not assume a map keeps the order you added pairs in, and remember that size() counts pairs, not keys and values separately. Also watch out for assigning get() of a missing key straight into an Integer, because the null you get back will throw as soon as you do math with it.

      Why This Matters

      Maps turn a slow search into an instant lookup. Instead of looping through a list of accounts to find the one with a given id, you build a map once and read any record straight out of it.

      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