Is there an efficient way to remove all map records that start with a specific prefix?
For example:
Map<String, Account> accMap = new MapMap <String, Account>();
accMap.put('Mr.A', new account());
accMap.put('Mr.B', new account());
accMap.put('Miss.B', new account());
and I want to remove the first 2 records from the map.
Should I run a for loop and check every key's prefix?
Best Answer
Salesforce does not provide us with a method to remove keys from a Map based on prefixes. The map type uses hashing to store keys in the data structure behind-the-scenes, which means any prefix would have a completely unrelated hash.
Unless you already have a set of map keys that you want to remove, I imagine that you would need to iterate over every map key.
As a simple example
edit: simple benchmark
Because I got a little curious, I did run some simple tests on the set + keySet().removeAll() approach vs just calling map's remove() method in the loop.
Here's the code I used to benchmark:
The first run was simply to warm up Salesforce's apex cache. After that, I performed 5 runs for each approach.
With a map of 100k size, I measured that it took
keySet().removeAll()
approach.remove()
in the loop approachThe varience in measured times for both approaches makes the difference insignificant, and that's even before you consider that this was done on a map of size 100k.
In real usage, there will be no measurable difference.