function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SabrentSabrent 

IgnoreCase when Key in map is a string

Is there a way to ignore the case when comparing string with a Map Key? 

 

I tried tolowercase (), toupperCase, but for my requirement that's not a viable solution. 

 

Any other way?

 

Map<string, string> colorCodes = new Map<String, String>();

string s1='RED';
string s2='BLUE';

 

colorCodes.put(s1.tolowercase(), 'FF0000');
colorCodes.put(s2.tolowercase(), '0000A0');

Boolean contains = colorCodes.containsKey('BluE');
System.assertEquals(contains, True);    // Assertion fails

sfdcfoxsfdcfox
The only maps that are case insensitive are those from getGlobalDescribe and getDescribe. All others are case sensitive. To implement case insensitive maps, you'd have to implement a custom key type, but that would probably even be more cumbersome than simply using tolowercase/touppercase. Or, you could write a map wrapper class, and that would allow you better control over the case sensitivity, but that isn't without its own drawbacks; you can't write parameterized classes, so you'd need to design a class that uses dynamic apex to support different types of data you could store.
Devender MDevender M

Hi raov,

 

As u r keeping the key in lower case, when your checking containskey convert that string also into lowercase. and then compare

sandeep@Salesforcesandeep@Salesforce

This is map's property wo can not hadel it even using "tolowercase()" , "toupperCase()" methods.

SabrentSabrent

Thank you everyone for your responses . Much appreciated.

 

I have thought of a work around. Will see how i go and post it here.

 

Thanks again.

 

David KingeryDavid Kingery
rov, I'd like to hear about your workaround if it worked.

I'm actually having the exact opposite problem, I'm comparing two Ids and coming up with false matches when the only difference is an upper-or-lowercase character.
Salesforce BeginnerSalesforce Beginner
rov,

Can you please let me know the workaround which you tried ? Were you able to handle this. I am in same situation like you. Waiting for your reply.
 
sumit mishra 5sumit mishra 5
one of the ways

 public map<string,object> convertTolowerAllkeys(Map<string,object> v){
      Map<string,object> newMap = new  map<string,object> ();
      for(string key : v.keySet()){
         newMap.put(key.toLowerCase(),v.get(key));
      }
      return newMap;
  }

 Map<String,Object> fieldMap =convertTolowerAllkeys(sobj.getPopulatedFieldsAsMap());