Lists of Opportunities
Write Apex · Beginner · 15 min · Runs in your Salesforce Developer org · Free
Scenario. A sales preview arranges proposed Opportunities before any record is saved.
Add, read and change in-memory Opportunities in a List, and read items only at safe positions.
What you will learn
A List<Opportunity> keeps records in order. add puts one at the end, [i] reads position i (the first is 0), and size() counts them.
opportunities.add(renewal);
Opportunity first = opportunities[0];
The List holds the same record, not a copy. Change opportunities[0].StageName and renewal.StageName changes too.
Gotcha. Reading a position outside 0 to size() - 1 throws an error. Check the index first.
The task
Put two Opportunities in a List, change one through the List, and read items only at safe positions.
Examples:
opportunities[0]→First name: Renewal- set the stage through the List →
Renewal stage: Qualification - index 1 →
Pick at 1: Expansion; index 2 and index -1 →Pick at 2: noneandPick at -1: none
Requirements:
- Add
renewalandexpansionto the List. PrintFirst name:from index 0 andList size:fromsize(). - Set
opportunities[0].StageNametoQualification, then printRenewal stage:from therenewalvariable. - For index 1, then 2, then -1, set
pickedto that item's Name only if the index is at least 0 and less thansize(). Otherwise set it tonone. - Print
Pick at 1:,Pick at 2:andPick at -1:withpickedfor each index.
Starter code
List<Opportunity> opportunities = new List<Opportunity>();
Opportunity renewal = new Opportunity(
Name = 'Renewal', StageName = 'Prospecting', CloseDate = Date.newInstance(2027, 6, 30)
);
Opportunity expansion = new Opportunity(
Name = 'Expansion', StageName = 'Prospecting', CloseDate = Date.newInstance(2027, 9, 30)
);
// Pick at 1
Integer requestedIndex = 1;
String picked = null;
// Pick at 2
requestedIndex = 2;
picked = null;
// Pick at -1
requestedIndex = -1;
picked = null;
When it passes
Renewal is first, the List holds 2 records, the stage change shows on `renewal` too, index 1 gives Expansion, and indexes 2 and -1 both give none.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.