Skip to main content

Define Sets and Maps

Learning Objectives

After completing this unit, you’ll be able to:

  • Create sets and maps.
  • Describe how lists, sets, and maps differ.
  • Decide when to use a set instead of a list.

Follow Along with Trail Together

Want to follow along with an expert as you work through this step? Take a look at this video, part of the Trail Together series on Trailhead Live. 

(This clip starts at the 49:06 minute mark, in case you want to rewind and watch the beginning of the step again.)

Introduction

As you already learned, a list is an ordered collection of items with the same data type. Each item has a position called an index. This makes it easy to retrieve items in the list by the numbered index. But Apex collections are more than just lists. The other two types of collections are sets and maps.

Sets

Until now, you’ve created one type of collection, a list. A set is an unordered set of unique items of the same type. Similar to a list, a set is a group of items, called elements, and all elements have the same data type, such as string, integer, or even Account. Unlike a list, a set maintains no particular order for its elements. Because the elements are unordered, a set can't have any duplicates. If you try to add an element that’s already in the set, you don’t get an error, but the new value is not added to the set. Remember that when you loop through a list, you always access its items in the order that the items were added to the list. When you loop through a set, because the elements are unordered, you may access elements in a random order.

Declaring a set is like declaring a list, but you substitute the keyword Set for List. Let’s create a set of strings.

Create a Set

  1. In the Developer Console, click File | New | Apex Class.
  2. Enter Tea for the class name.
  3. Click OK.
  4. Replace the code in the Tea class with this code:
    public class Tea{
        public static void orderTea(){
            Set<String> teaTypes = new Set <String>();
            teaTypes.add('Black');
            teaTypes.add('White');
            teaTypes.add('Herbal');
            system.debug(teaTypes);
        }
    }
  5. Click File | Save.

Run the Code

  1. Click Debug | Open Execute Anonymous Window.
  2. In the Enter Apex Code window, paste this code:
              Tea.orderTea();
  3. Select Open log and then click Execute. The Execution Log opens, displaying the results of running your code.
  4. Select Debug Only at the bottom of the window.

The debug log shows the three tea types: Black, White, and Herbal.

Set Methods

Each type of collection has its own methods. You added Black, White, and Herbal to a list of tea types with the commonly used add method. To learn more about set methods, see the Resources at the end of this unit.

Add a Duplicate Value to a Set

  1. In the Tea class, replace the orderTea method (lines 2–8) with this code:
    public static void orderTea(){
        Set<String> teaTypes = new Set <String>{'Black', 'White', 'Herbal'};
        system.debug(teaTypes);
        teaTypes.add('Green');
        teaTypes.add('Black');
        system.debug(teaTypes);
    }
  2. Click File | Save.

Run the Code

  1. Run this code: Tea.orderTea();
    Tip: Click Debug | Execute Last to rerun code that you’ve already run using Execute Anonymous. This option is convenient when you make changes to a method and rerun it the same way.
  2. Review the debug log.

Line 4 displays teaTypes in the log so you can check the contents of the set. Lines 6 and 7 add Green and Black to the set. Line 9 displays teaTypes in the log so you can check the contents of the set again. Why wasn’t Black added to the set? 

Remember that sets don’t allow repeated values. Also, keep in mind you can’t index a set like you can with a List. Sets are typically used for checking if a certain value is included.

Choosing a List or a Set

You may be thinking, “I know how to use both lists and sets now. How do I decide which to use?” Think about the collection you want to create and ask yourself these two questions.

  1. Do I want to allow duplicates?
  2. Is the order of items important?

If you answer yes to at least one of these questions, then use a list. If you answer no to both questions, use a set. 

You’ve learned about lists and sets, but there’s one more collection type. Let’s talk about maps next.

Maps

A map is a more complex collection than either a list or a set. Each item in a map has two parts: a key and a value, known as a key-value pair. Keys and values can be any data type. Although each key is unique, values can be repeated within a map. Imagine a map of telephone country codes. The country code is the key and the name of the country is the value. Each country code is unique, but the countries can be duplicated (because a country may have more than one country code). 

The Put Method

To add key-value pairs to a map, use the put method, like this:

mapName.put (key, value);

The put method expects two parameters: key and value. Let’s create a map of tea types (keys) and their flavor profiles (values). 

Tea Types and Flavor Profiles

Tea Types (Key)
Flavor Profile (Value)
Black
Earthy
Herbal
Sweet
White
Sweet

Create a Map

  1. In Tea class, replace the existing code with this code:
    public class Tea{
        public static void orderTea(){
            Map <String, String> teaTypes = new Map <String, String>();
            teaTypes.put('Black', 'Earthy');
            teaTypes.put('White', 'Sweet');
            teaTypes.put('Herbal', 'Sweet');
            system.debug(teaTypes);
        }
    }
  2. Click File | Save.

Run the Code

  1. Run this code: Tea.orderTea();
  2. Review the debug log.

The debug log shows that the map has three key value pairs:

Black=Earthy, Herbal=Sweet, White=Sweet

The values Earthy and Sweet are the flavor profiles. Sweet is the flavor profile for two tea types because duplicate values are allowed in a map.

The Get Method

To access values in a map, use the get method, like this: 

mapName.get (key);

When provided with an existing key, the get method returns the value of the key. If the provided key is not mapped to a value, the get method returns null. Remember that the map declaration specifies the data type it expects for a return value. The variable that returns a value must be the same data type that the map declaration specifies.

Get Values from a Map

  1. In the Tea class, replace the orderTea method (lines 2–8) with this code:
    public static String orderTea(){
        Map <String, String> teaTypes = new Map <String, String>();
        teaTypes.put('Black', 'Earthy');
        teaTypes.put('White', 'Sweet');
        teaTypes.put('Herbal', 'Sweet');
        String flavorProfile = teaTypes.get('Herbal');
        System.debug('The flavorProfile of Herbal is: ' + flavorProfile);
        return flavorProfile;
    }
  2. Click File | Save.

Run the Code

  1. Run this code:  Tea.orderTea();
  2. Review the debug log.

Because the teaTypes map is declared with string values, the return type must also be a string (flavorProfile).

Now you know about all three types of Apex collections. 

Collection Type
Description
List
An ordered group of items of the same type. Each item has an index number that represents its position in the list.
Set
An unordered group of unique items of the same type.
Map
A collection of key-value pairs. Each unique key maps to a single value.

In more advanced modules you begin to query data within your org. Once your data is received you need places to store information; collections are helpful with providing temporary storage. If you want to learn more about collections check out the Apex Developer Guide links in the Resources section. 

Resources

在 Salesforce 帮助中分享 Trailhead 反馈

我们很想听听您使用 Trailhead 的经验——您现在可以随时从 Salesforce 帮助网站访问新的反馈表单。

了解更多 继续分享反馈