Skip to main content

Collections: List, Set, Map

Apex Collections: List, Set, Map

Apex provides three powerful types of collections to handle groups of data: List, Set, and Map. These collections help manage bulk records, loop through data, and perform DML operations efficiently.


1️⃣ List in Apex

A List is an ordered collection of elements that allows duplicates. It's similar to an array in other languages.

Example: List

List fruits = new List();
fruits.add('Apple');
fruits.add('Banana');
fruits.add('Apple'); // Duplicate allowed

System.debug(fruits); 
System.debug(fruits[0]); // Access by index
  

🔸 Common List Methods:

  • add(value)
  • get(index)
  • size()
  • contains(value)

2️⃣ Set in Apex

A Set is an unordered collection that contains only unique elements.

Example: Set

Set countries = new Set();
countries.add('India');
countries.add('USA');
countries.add('India'); // Ignored (duplicate)

System.debug(countries);
System.debug(countries.contains('USA')); // true
  

🔸 Common Set Methods:

  • add(value)
  • contains(value)
  • remove(value)
  • size()

3️⃣ Map in Apex

A Map is a collection of key-value pairs. Keys must be unique, but values can be duplicated.

Example: Map

Map studentMap = new Map();
studentMap.put(101, 'John');
studentMap.put(102, 'Alice');
studentMap.put(101, 'Mike'); // Overwrites John

System.debug(studentMap);
System.debug(studentMap.get(101)); // Output: Mike
  

🔸 Common Map Methods:

  • put(key, value)
  • get(key)
  • keySet()
  • values()

📊 Comparison Table

Collection Order Duplicates Allowed Use Case
List Ordered Yes Store multiple values with index access
Set Unordered No Ensure all values are unique
Map Key-based Keys: No
Values: Yes
Store key-value pairs

🔍 When to Use What?

  • List - When order and duplicates matter (e.g., a sequence of records).
  • Set - When you need uniqueness (e.g., deduping email IDs).
  • Map - When mapping one value to another (e.g., Id ➝ Name).