I have two maps like below:

Map<String,Set<Id>> emailMatchingContacts = new Map<String,Set<Id>>();
Map<String,Set<Id>> epostMatchingContacts = new Map<String,Set<Id>>();

I've loaded some keys and values to the maps. Now I'm trying to get all the contact id's added in this maps. Tried with minimum possible code like below

Set<Id> matchingContactIds = new Set<Id>();

but it was throwing an error like below

Illegal assignment from List<Set<Id>> to Set<Id>

Is that apex standard behavior, loading the map values into List by default?

  • Error states, you would need to iterate over map to add set from each value
    – Raul
    Aug 22, 2019 at 13:18
  • When in doubt, I'd recommend consulting the documentation as a first step.
    – Derek F
    Aug 22, 2019 at 13:30

2 Answers 2


emailMatchingContacts.values() will return List of the values of Map from key-value pairs. That will be List<Set<Id>>

This will be resolved by either 1 of them:

  • emailMatchingContacts should be of type Map<String,Id> OR .
  • you should do matchingContactIds.addAll(emailMatchingContacts.get(key))

emailMatchingContacts.get(key) will return Set<Id> from a given item which has key as key. PFB:

for(String key : emailMatchingContacts.keySet()) {
  • Thanks, I'm doing the same now.
    – Lokesh
    Aug 22, 2019 at 13:27
  • 1
    You can just loop over values() since you don't actually care about the key.
    – Adrian Larson
    Aug 22, 2019 at 23:11

Map's values() method will give you the List<Values> which in your case is Set<Id>. So, when you do emailMatchingContacts.values(), you will get List<Set<Id>>.

And Set's addAll method takes input as List<elements> or Set<elements>and not List<Set<elements>>

So, best possible way I can think of achieving your requirement is by iterating over the values and adding all the elements one by one.

for(Set<Id> ids : emailMatchingContacts.values()){

You must log in to answer this question.

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