Case Insensitive HashMap
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