Ley*_*nho 6 java hashmap ignore-case
我试图检查我的hashmap键集是否包含字符串'buffSB.toString()'.但我想比较忽略的情况(上部或下部).
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());
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激!!!
如果您看到 HashMap getKey 方法的实现,您必须传递正确的键来生成哈希值并从该存储桶中获取实际值。
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;
Run Code Online (Sandbox Code Playgroud)
三种解决方案
Map<String, String> pref = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
Run Code Online (Sandbox Code Playgroud)
或者
Map<String, String> map = new CaseInsensitiveMap<String, String>();
Run Code Online (Sandbox Code Playgroud)
或者
Looping through map with the ignore case
Run Code Online (Sandbox Code Playgroud)