6

我正在尝试检查我的 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());
  }

任何帮助将不胜感激!!!

4

6 回答 6

2

您还可以尝试使用 TreeMap ,它可以为其构造函数提供比较器:

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

请参阅不区分大小写的字符串作为 HashMap 键

于 2015-11-20T14:49:48.380 回答
2

您可以使用CaseInsensitiveMap<K,V>而不是Map<K,V>

它扩展AbstractHashedMap<K,V>并忽略了键的大小写。您可以通过将现有的区分大小写的映射传递给构造函数来创建此映射的新实例。

考虑这个例子:

Map<String, String> map = new CaseInsensitiveMap<String, String>();
map.put("One", "One");
map.put("Two", "Two");
map.put(null, "Three");
map.put("one", "Four");

该地图将包含三个元素:

<one, "Four">
<two, "Two">
<null, "Three">

事实上map.put("one", "Four")用 覆盖值插入map.put("One", "One")

map.get(null)返回“三”。

map.get("ONE"), map.get("one"), map.get("One"), 等等返回“四”。

请记住,该keySet()方法返回所有小写键或空值。

keySet()等于{"one", "two", null}

更多文件

于 2015-11-22T17:30:13.650 回答
1

仅使用小写键:

map.put(key.toLowercase(), value);
// later
String val = map.get(someKey.toLowerCase());
于 2015-11-20T14:38:22.850 回答
1

您可以循环遍历keySet地图,对于每个键,使用字符串函数equalsIgnoreCase进行比较:

    Map<String, String> pref = new Datamatch().main();  // Getting the Hashmap from other class

    String val;
    for (String key : pref.keySet()) {
        if (key.equalsIgnoreCase(buffSB.toString())) {
            val = pref.get(key);
            break;
        }
    }
于 2015-11-20T14:38:33.310 回答
1

如果您看到 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;

三种解决方案

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

或者

    Map<String, String> map = new CaseInsensitiveMap<String, String>();

或者

    Looping through map with the ignore case
于 2015-11-23T07:33:05.127 回答
-1
pref.containsKey(buffSB.toString().toLowerCase())

使用 string.toUpperCase() 或 string.toLowerCase() 忽略大小写。

于 2015-11-20T14:35:00.713 回答