I have two maps, and am currently using a nested for loop to compare the keys of one map with the values of the other, and then placing the matching info into a new map. Is there a more efficient way to do this without a nested for loop?

                //Connect the Program Id to the Group Definitions Id (Group Definition Id key, program Id value)
                for(Id assignId: groupAssignmentIds.keyset()){
                    for(Id groupDefId: groupDefinitionIds.keyset()){
                        if(assignId == groupAssignmentIds.get(groupDefId)){
                            groupProgramIds.put(groupDefId, groupAssignmentIds.get(assignId));    
  • Are you sure that logic is correct? You're looping over the keySet() from groupDefinitionIds, but you never actually access that map. Should it be if(assignId == groupDefinitionIds.get(groupDefId)){?
    – David Reed
    Jun 4, 2018 at 17:10

1 Answer 1


Yes, there is.

You can use the containsKey() method of the map class.

    // Iterate over just one of your maps
    for(Id groupDefId: groupDefinitionIds.keyset()){
        // Assuming the keys in both maps are the same, you can simply use
        //   containsKey()
        // By "same keys", I mean that a key from one map can exist in the other.
        // This wouldn't work if, for example, one map held Account Ids, and the
        //   other held Opportunity Ids
            groupProgramIds.put(groupDefId, groupAssignmentIds.get(assignId));    

There's even a way that you can avoid having any explicit loop at all! (I say "explicit" loop, because the back-end implementation of at least some of the collection class methods probably involves a loop of its own)

// Step 1, clone the map you want to use the values from
Map<Id, MyClass> groupProgramIds = groupAssignmentIds.clone();

// Step 2, keeping/removing keys from a map removes the access to the associated values as well.
// map.keySet().removeAll()/retainAll() does just that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.