Case insensitive string as HashMap key Case insensitive string as HashMap key java java

Case insensitive string as HashMap key


Map<String, String> nodeMap =     new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

That's really all you need.


As suggested by Guido GarcĂ­a in their answer here:

import java.util.HashMap;public class CaseInsensitiveMap extends HashMap<String, String> {    @Override    public String put(String key, String value) {       return super.put(key.toLowerCase(), value);    }    // not @Override because that would require the key parameter to be of type Object    public String get(String key) {       return super.get(key.toLowerCase());    }}

Or

https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/CaseInsensitiveMap.html


One approach is to create a custom subclass of the Apache Commons AbstractHashedMap class, overriding the hash and isEqualKeys methods to perform case insensitive hashing and comparison of keys. (Note - I've never tried this myself ...)

This avoids the overhead of creating new objects each time you need to do a map lookup or update. And the common Map operations should O(1) ... just like a regular HashMap.

And if you are prepared to accept the implementation choices they have made, the Apache Commons CaseInsensitiveMap does the work of customizing / specializing AbstractHashedMap for you.


But if O(logN) get and put operations are acceptable, a TreeMap with a case insensitive string comparator is an option; e.g. using String.CASE_INSENSITIVE_ORDER.

And if you don't mind creating a new temporary String object each time you do a put or get, then Vishal's answer is just fine. (Though, I note that you wouldn't be preserving the original case of the keys if you did that ...)