I am trying to check if my hashmap key set contains the string 'buffSB.toString()'. But I wanted to compare ignoring case (upper or lower).
static StringBuilder buffSB = new StringBuilder();
buffSB.append(alphabet);
Map<String, String> pref = new Datamatch().main(); // Getting the Hashmap from other class
if(pref.containsKey(buffSB.toString())) //This is where I need to ignore case while searching string in the map key set
{
String val = pref.get(buffSB.toString());
}
Any help will be greatly appreciated!!!
If you see the implementation of HashMap getKey method you have to pass the proper key to generate the hash value and get the actual value from that bucket.
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
Three solutions
Map<String, String> pref = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
OR
Map<String, String> map = new CaseInsensitiveMap<String, String>();
OR
Looping through map with the ignore case