Is there an easy way to extract the list of objects from a map containing list of objects? For ex, below is an example map that I need to deal with.

map<Id, List<Contact>> accountWithContacts = new map<Id, List<Contact>>();

Assuming that this map is populated with an accountId and the contacts that belong to the accountId, how to extract the List from the map? I could not find any method in the map class that returns a list.

Can someone help?

1 Answer 1


There is no simple one-line method (as in JavaScript, where we can e.g. Array.prototype.flat), its most simple form would be:

List<Contact> allContacts = new List<Contact>();
for(List<Contact> contacts: accountWithContacts.values()) {
  • 1
    Needs addAll?
    – Keith C
    Apr 11, 2021 at 8:55
  • @KeithC Whoops. Fixed. Thanks for the catch.
    – sfdcfox
    Apr 11, 2021 at 14:56
  • Thank you very much. Apr 13, 2021 at 4:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .