Beginner 15 min read

What Is a Collection?

By the end of this lesson, you'll be able to:

  • Explain what a collection is and why a single variable per value doesn't scale
  • Name Apex's three collection types: List, Set, and Map
  • Recognize when a problem calls for a collection instead of individual variables

Prerequisites: Module 14: "Professional Engineering Practices I"

The problem: one variable per value doesn't scale

String customer1 = 'Amara';
String customer2 = 'Ben';
String customer3 = 'Carla';
// ...what about customer 500?

This breaks down immediately past a handful of values, and it's completely unworkable when the count isn't known until runtime — like every Account a SOQL query happens to return. A collection solves this: one variable that holds many values at once.

Apex's three collection types, previewed

  • List — an ordered collection that allows duplicates. Covered in depth for the rest of this module.
  • Set — an unordered collection with no duplicates.
  • Map — key-value pairs, for looking values up by a key.

The next module goes deep on Set and Map; this one focuses entirely on List, the collection type you'll reach for by default.

Exercise

As a comment, explain why writing customer1, customer2, customer3... doesn't work for data returned from a SOQL query.

Show hint

Think about whether you know the count in advance.

APEX

What Is a Collection? Quiz

1. What is a collection?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

A collection holds many values in a single variable — Apex provides three kinds (List, Set, Map), each suited to a different job, starting with List in this module.