Case Insensitive HashMap

 

Array with Even and Odd numbers

This is one of the programming interview questions which asked in recent interview. Need to implement HashMap which will take case insensitive keys. Here we should not confuse with case sensitive, since HashMap by default will hold keys with case sensitive. But as an alternate we need to implement HashMap with Case Insensitive. 
For example: We need to store "abc" and "ABc" in key. Default HashMap will have 2 entries since its case sensitive, where as we need to store only 1 key and value with "abc" with case insensitive. 

So how we can define HashMap with case insensitive? 

We can implement in various ways like implementing Map interface or extending HashMap class etc., In below example we will see about implementing Case Insensitive HashMap by extending HashMap class.


import java.util.HashMap;
import java.util.Map;

public class HashMapCaseInsensitive extends HashMap<String, String>{
 
 @Override
 public String put(String key, String value) {
  return super.put(key.toLowerCase(), value);
 }

 @Override
 public String get(Object key) {
  return super.get(key.toString().toLowerCase());
 }
 
 public static void main(String[] args) {
  
  Map<String, String> hm = new HashMapCaseInsensitive();
  
  hm.put("abc", "one");
  hm.put("ABc", "two");
  hm.put("aBc", "three");
  
  System.out.println("HASHMAP SIZE  : "+hm.size());
  
  System.out.println("GET ABC VALUE : "+hm.get("ABC"));
 }
}


OUTPUT:


HASHMAP SIZE  : 1
GET ABC VALUE : three









1 comment:
Write comments