简体   繁体   中英

CaseInsensitive search in HashMap

I have a map:

static Map<String, String> = getMap(); //getting a map from a config file.

Now in this Map I need to perform a caseInsensitive search, using KEYS. I am NOT putting the values in map, not through put function, but you can think it as a values stored in data base in a key value format, and retrieving it as a Map. I need to do a caseInsentive search.

After researching, using a TreeMap would solve the problem, but not efficient --> O(log n)

or overring the get() method of HashMap, creating my own HashMap. but this would include overrding many methods, and I dont want this much, it not a part of very important code.

Right now I am im storing the values, in lowercase in database, and checking. But it makes it error prone, and not readble, in database.

Can there be a simpler method to do it?

1.) TreeMap extends Map can be an option, but time complexity is O(log n)

final Map<String, Object> map = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);

2.) You could use CaseInsensitiveMap from Apache's Commons Collections as suggested above.

3.) Creating your own HashMap Class and overriding methods.

public class MyCaseInsensitiveMap extends HashMap<String, String> {
    ...
    put(String key, String value) {
       super.put(key.toLowerCase(), value);
    }

    get(String key) {
       super.get(key.toLowercase());
    }
}

4.) You need a wrapper class for your String key with a case-insensitive equals() and hashCode() implementation. Use that instead of the String for the Map's key.

example here

** There does not seems to be straight forward library available except for apache commons.

PS: Consolidated from other links available in SO also.

If you are fine with O(1) but utilizing more space, this may help:

class CaseInsensitiveLookupMap {

private Map<String,String> keysMap = new HashMap<String,String>();
private Map<String,String> dataMap;

public CaseInsensitiveLookupMap(Map<String,String> dataMap){
  this.dataMap=dataMap;
  for(String key: dataMap.keySet()){
     keysMap.put(key.toLowerCase(),key);
  }
}

public String get(String keyToSearch){
  String _key = keysMap.get(keyToSearch.toLowerCase());
  if(_key!=null) {
    return dataMap.get(_key);
  }
  return null;
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM