2

I have Map A which is a subset of Map B. Now I want to remove those elements of Map A from Map B. Is that possible to be done?

1
  • Please, give us wider example, probably with code providing.
    – EvAzi
    Dec 2 '16 at 11:13
5

You can use the remove() method:

Map <String, String> mapOne = new Map <String, String>();
mapOne.put('key1', 'value1');
mapOne.put('key2', 'value2');
mapOne.put('key3', 'value3');
mapOne.put('key4', 'value4');

Map <String, String> mapTwo = new Map <String, String>();
mapTwo.put('key1', 'value1');
mapTwo.put('key2', 'value2');

for (String key : mapTwo.keySet())
{
    mapOne.remove(key);
}

Now mapOne will only contain key3=>value3 and key4=>value4. This example is if the keys of the maps match.

If you want to remove elements from one map based on values from another, then instead of keySet() just use values().

Docs

1

A clear and efficient solution would be by using keySet() and removeAll() methods.

Explanation:

map.keyset() will return a reference to the set of keys of the respective map, enabling the interface to use set class methods. which in turn allows us to use the removeAll() method to remove all the keys from the map at once.

Example:

Map <String, String> mapOne = new Map <String, String>();
mapOne.put('key1', 'value1');
mapOne.put('key2', 'value2');
mapOne.put('key3', 'value3');
mapOne.put('key4', 'value4');

Map <String, String> mapTwo = new Map <String, String>();
mapTwo.put('key1', 'value1');
mapTwo.put('key2', 'value2');

System.debug(mapOne);
mapOne.keySet().removeAll(mapTwo.keyset()); // removing elements from map
System.debug(mapOne);

enter image description here

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.