⚡ Code it · 40 XP
Lists, Sets and Maps
Lists, Sets and Maps
These three collections are the backbone of every bulk-safe Apex program.
List: ordered, allows duplicates
List<String> heroes = new List<String>{'Nomsa', 'Sipho'};
heroes.add('Thandi');
String first = heroes[0]; // or heroes.get(0)
Integer n = heroes.size();
A SOQL query returns a List<SObject>. You'll use Lists constantly.
Set: unordered, unique values
Set<Id> accountIds = new Set<Id>();
accountIds.add(someId);
accountIds.add(someId); // ignored, already there
Boolean has = accountIds.contains(someId);
Set<String> fromList = new Set<String>(heroes); // dedupe a list
Sets are perfect for collecting Ids to use in WHERE Id IN :accountIds.
Map: key → value
Map<String, Integer> xpByHero = new Map<String, Integer>();
xpByHero.put('Nomsa', 120);
Integer xp = xpByHero.get('Nomsa'); // 120
Integer missing = xpByHero.get('Bob'); // null, not an error
Boolean known = xpByHero.containsKey('Nomsa');
And the most useful constructor in all of Apex:
Map<Id, Account> accountsById = new Map<Id, Account>([SELECT Id, Name FROM Account]);
Your mission
loot already exists. Build uniqueLoot (a Set) and lootCounts (a Map counting each item).
🦝 Maps are Quill's favourite data structure. You'll understand why in the bulkification chapter.