List<Account> al = [SELECT Id FROM Account];
List<Contact> cl = [SELECT Id, AccountId FROM Contact];
// Map to associate each Account Id with its corresponding Contacts
Map<Id, List<Contact>> accountContactMap = new Map<Id, List<Contact>>();
// Populate the map
for (Contact c : cl) {
if (!accountContactMap.containsKey(c.AccountId)) {
accountContactMap.put(c.AccountId, new List<Contact>());
}
accountContactMap.get(c.AccountId).add(c);
}
// Iterate through Accounts and their Contacts using the map
for (Account a : al) {
if (accountContactMap.containsKey(a.Id)) {
List<Contact> contacts = accountContactMap.get(a.Id);
for (Contact c : contacts) {
// Perform work here with Account a and Contact c
}
}
}
The answer is D. You should retrieve the child contact data along with the parent:
[SELECT Id ,(SELECT Id, AccountId FROM Contact) From Account];
This will return a nested list of objects (answer D)
Ref: https://medium.com/code-85/how-to-query-parent-and-child-relationships-in-soql-13445ace3c7f
[SELECT Id ,(SELECT Id, AccountId FROM Contact) From Account]
Wouldn't this return a list of accounts containing each a list of contacts?!
I don't seem it would return a Map<Id,List<Contact>>, at most a Map<Id,Account> where each account would contain its own contacts..
How does using the Map really help here? The problem is that we're retrieving all the accounts and all the contacts and then iterating through all the contacts for each account.
bottleneck is nested loop. You should avoid nested loop whenever possible.
upvoted 1 times
...
...
Log in to ExamTopics
Sign in:
Community vote distribution
A (35%)
C (25%)
B (20%)
Other
Most Voted
A voting comment increases the vote count for the chosen answer by one.
Upvoting a comment with a selected answer will also increase the vote count towards that answer by one.
So if you see a comment that you already agree with, you can upvote it instead of posting a new comment.
ABHI0O07
8 months agoedogaldo
1 year, 2 months ago1vanTT
1 year, 6 months agoedogaldo
1 year, 2 months agogovosen887
1 year, 7 months agomwwt2022
1 year, 1 month ago