ApexSensei

Drills › Write Apex

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: none and Pick at -1: none

Requirements:

  1. Add renewal and expansion to the List. Print First name: from index 0 and List size: from size().
  2. Set opportunities[0].StageName to Qualification, then print Renewal stage: from the renewal variable.
  3. For index 1, then 2, then -1, set picked to that item's Name only if the index is at least 0 and less than size(). Otherwise set it to none.
  4. Print Pick at 1:, Pick at 2: and Pick at -1: with picked for 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.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ While a queue has work · Maps: Id to Account ›