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
    Commented Dec 2, 2016 at 11:13

2 Answers 2

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

5

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

1
  • This should be marked as the best answer. No need for loops here! Commented Jul 19, 2022 at 8:55

You must log in to answer this question.

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