[SalesForce] Compare Value of One Map with Key of Another Map to create new Map

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?

            if(groupDefinitionIds.size()>0){
                //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));    
                        }
                    }
                }     

Best Answer

Yes, there is.

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

if(groupDefinitionIds.size()>0){
    // 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
        if(groupAssignmentIds.containsKey(groupDefId)){
            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
groupProgram.keySet().retainAll(groupDefinitionIds.keySet());