Apex Maps Keys are case sensitive

I use Maps a lot when I write code, usually to help me reduce the number of times I have to do queries. Normally they work just fine and I don’t pay attention to the little details like the case of the text used in its keys. The other day though, I was getting some really weird results from my code. The code was being used to dedupe incoming records against existing ones. I started by compiling the unique IDs for the new records, then queried existing records with the same ids, and then created a map of the Unique Id to existing record. Pretty straightforward simple stuff, right.

Well, for some reason my code didn’t work for one record. Since it was one record I knew it had to be data related, but a quick glance at the new record and the existing one didn’t yield any differences. A more thorough glance though revealed one letter that was lowercase where it should’ve been uppercase. It didn’t seem like that could be the problem, after all, text == TEXT results in TRUE. Well, it turns out that map.containsKey() is case sensitive and there’s no attribute that can be set to change this.

The solution is pretty simple, before putting a key into the map you use either string.touppercase() or string.tolowercase() to standardize the keys. Then when you use map.containsKey(), you use the same method to standardize the string you’re looking for.
After figuring this out myself, I found a post about it over at The Silver Lining. Sure wish it were in the developer docs!

Related posts:

  1. Properly Formatting Names in Apex
  2. Converting Strings to Integers with Apex
  3. Dynamic Queries with Apex
  4. Apex Describe with Dynamic SOQl
  5. Validating email addresses in Apex

Post a Comment