Collections in Apex: A Beginner’s Guide

Collections are a powerful tool in any programming language, including Salesforce’s Apex. They allow developers to store, organize, and manipulate multiple pieces of data efficiently. Whether you’re working with a list of records, a set of unique values, or key-value pairs, collections provide a structured way to handle bulk data processing in Salesforce.

In this guide, we’ll explore collections in Apex, including the types of collections available, how to use them, and some practical examples. This article is designed to be beginner-friendly and SEO-optimized for students with little or no programming experience.

What is a Collection and Why Do We Use It?

A collection is a data structure that groups multiple elements together, such as numbers, strings, or objects. Collections are particularly useful when dealing with Salesforce records or large amounts of data, as they help developers process, manipulate, and iterate through many items at once without having to handle each individually.

Why do we use collections?

  • Efficiency: Collections allow you to handle large amounts of data with ease, reducing the complexity of your code.
  • Flexibility: They let you add, remove, and update elements in bulk, making your code more adaptable.
  • Organized Data: Collections help in grouping related data and accessing it efficiently.

Types of Collections in Apex

Apex provides three primary types of collections: Lists, Sets, and Maps. Each of these serves different purposes based on the type of data and how you want to organize it.

List – A List is an ordered collection of elements, where each element is indexed. This means you can access elements based on their position in the list. Lists can contain duplicate values, and the insertion order is preserved.

Example:

List<string> cities = new List<string>{'New York', 'Los Angeles', 'Chicago'};
System.debug(cities[0]); // Outputs 'New York'</string></string>

Uses:

  • Storing multiple elements where the order is important.
  • Accessing elements by their index or position.

Set – A Set is an unordered collection of unique elements. Sets do not allow duplicates, and the insertion order is not preserved. This means you can’t access elements by index in a set.

Example:

Set<string> fruits = new Set<string>{'Apple', 'Banana', 'Orange', 'Apple'};
System.debug(fruits); // Outputs 'Apple', 'Banana', 'Orange' (removes duplicates)</string></string>

Uses:

  • Ensuring all elements are unique.
  • Fast lookups for checking if an element exists.

Map A Map is a collection of key-value pairs, where each key is unique and maps to a specific value. Maps are used when you need to associate one item (key) with another (value), making it easy to retrieve values based on their corresponding keys.

Example:

Map<String, Integer> cityPopulation = new Map<String, Integer>{'New York' => 8175133, 'Los Angeles' => 3792621};
System.debug(cityPopulation.get('New York')); // Outputs 8175133

Uses:

  • Storing key-value pairs where the key is unique.
  • Efficiently retrieving data based on a specific key.

Using For-Each Loop to Iterate Collections

Apex provides an efficient way to iterate over elements in a collection using the for-each loop. This type of loop allows you to go through each element in a collection without needing to manage indices or keys manually.

Example:

Iterating through a list of cities:

List<String> cities = new List<String>{'New York', 'Los Angeles', 'Chicago'};
for (String city : cities) {
    System.debug(city);
    }

For a Set:

Set<String> fruits = new Set<String>{'Apple', 'Banana', 'Orange'};
for (String fruit : fruits){
    System.debug(fruit)
    }

For a Map:

Map<String, Integer> cityPopulation = new Map<String, Integer>{'New York' => 8175133, 'Los Angeles' => 3792621};
for (String city : cityPopulation.keySet()){
    System.debug(city + ': ' + cityPopulation.get(city));
    }

Nested Collections

Nested collections are collections within collections. They are useful when handling complex data structures, such as when you need to manage lists of maps or sets of lists.

Example:

List<Map<String, Integer>> cityData = new List<Map<String, Integer>>();
Map<String, Integer> city1 = new Map<String, Integer>{'New York' => 8175133};
Map<String, Integer> city2 = new Map<String, Integer>{'Los Angeles' => 3792621};
cityData.add(city1);
cityData.add(city2);
for (Map<String, Integer> cityMap : cityData){
   for (String city : cityMap.keySet()){
       System.debug(city + ': ' + cityMap.get(city));
       }
   }

In this example, we have a list of maps, and the for-each loop helps us iterate through both the list and the maps to print out the city names and their populations.

List as Indexed Collection

A List is an indexed collection, meaning you can access each element by its position in the list. The index starts at 0, and the insertion order is always preserved, meaning elements will appear in the same order they were added.

Example:

List<String> names = new List<String>{'Alice', 'Bob', 'Charlie'};
System.debug(names[1]); // Outputs 'Bob'

Lists are great when you need to maintain the order of elements and access them by their position.

Set as Non-Indexed Collection

A Set is a non-indexed collection, where the insertion order is not preserved, and duplicates are automatically removed. This means you cannot access elements by index, and their order is unpredictable.

Example:

Set<String> carBrands = new Set<String>{'Toyota', 'Honda', 'Toyota', 'Ford'};
System.debug(carBrands); // Outputs 'Toyota', 'Honda', 'Ford' (duplicates removed)

Sets are useful when you need to store unique values and don’t care about the order.

Useful Methods for Collections

List Methods:

  • add(): Adds an element to the list.
  • remove(): Removes an element from a specific index.
  • size(): Returns the number of elements in the list.
  • isEmpty(): Returns true if the list has zero elements.

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_list.htm

List<String> names = new List<String>();
names.add('David');
System.debug(names.size()); // Outputs the total number of names in the list.

Set Methods:

  • add(elem): Adds an element to the set (only if it’s unique).
  • contains(elem): Checks if an element exists in the set.
  • remove(elem): Removes an element from the set.
  • isEmpty(): Returns true if the set has zero elements.

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_set.htm

Set<String> carBrands = new Set<String>();
carBrands.add('Chevrolet');
System.debug(carBrands.contains('Toyota')); // Outputs true if 'Toyota' is in the set.

Map Methods:

  • put(key, value): Adds a key-value pair to the map.
  • get(key): Retrieves the value associated with a specific key.
  • remove(key): Removes a key-value pair from the map.
  • containsKey(key): Returns true if the map contains a mapping for the specified key.
  • keySet(): Returns a set that contains all of the keys in the map.
  • values(): Returns a list that contains all the values in the map.
  • isEmpty(): Returns true if the map has zero key-value pairs.

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_map.htm

Map<String,Integer> cityPopulation = new Map<String, Integer>();
cityPopulation.put('Chicago', 2716000);
System.debug(cityPopulation.get('Chicago')); // Outputs the population of Chicago.

Practice Problems

  1. Problem 1: Create a list of integers and print all the even numbers from the list.
  2. Problem 2: Create a set of strings representing car brands and check if ‘Ford’ is in the set.
  3. Problem 3: Create a map that stores country names as keys and their populations as values. Retrieve and print the population of India.
  4. Problem 4: Use a nested list to store sales data for two teams. Each team has a list of monthly sales figures. Print the total sales for each team.
  5. Problem 5: Write a program that iterates through a map and prints the key-value pairs where the value is greater than 5000.

Conclusion

Collections are an essential part of Salesforce Apex programming. They help you organize, manipulate, and iterate over large amounts of data efficiently. Whether you’re using Lists for ordered data, Sets for unique elements, or Maps for key-value pairs, understanding how collections work will significantly improve your ability to handle bulk data in Salesforce. Make sure to practice the examples and problems to strengthen your knowledge and become proficient in using collections in Apex.