0

可能重复:
不区分大小写的字符串作为 HashMap 键

我有一个 Hashmap,其中一个字符串作为键,一个整数作为值。现在,我使用 get 方法来获取值,其中字符串与键值匹配。


HashMap<String,Integer> map= new HashMap<String,Integer>();
// Populate the map

System.out.println(map.get("mystring"));

我希望这个字符串比较不区分大小写。反正我能做到吗?


例如,我希望它在以下情况下返回相同的结果:


map.get("hello");
map.get("HELLO");
map.get("Hello");
4

5 回答 5

3

如果性能不重要,您可以使用TreeMap。以下代码的输出:

1
6
6

请注意,您需要的行为不符合Map#get合同

更正式地说,如果此映射包含从键 k 到值 v 的映射,使得 (key==null ? k==null : key.equals(k)),则此方法返回 v;否则返回null。(最多可以有一个这样的映射。)

public static void main(String[] args) {
    Map<String, Integer> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

    map.put("hello", 3);
    map.put("HELLO", 6);
    System.out.println(map.size());
    System.out.println(map.get("heLLO"));
    System.out.println(map.get("hello"));
}
于 2012-09-25T17:22:29.400 回答
1

你可以做

Map<String,Integer> map= new HashMap<String,Integer>() {
    @Override
    public Integer put(String key, Integer value) {
      return super.put(key.toLowerCase(), value);
    }

    @Override
    public Integer get(Object o) {
       return super.get(o.toString().toLowerCase());
    }
};
于 2012-09-25T17:18:23.973 回答
1

您可以创建一个包装类来包装 HashMap 并实现 get 和 put 方法。

于 2012-09-25T17:18:45.030 回答
1
HashMap<InsensitiveString,Integer> map= new HashMap<>();

map.get(new InsensitiveString("mystring"));

---

public class InsensitiveString

    final String string;

    public InsensitiveString(String string)
        this.string = string;

    public int hashCode()
        calculate hash code based on lower case of chars in string

    public boolean equals(Object that)
        compare 2 strings insensitively
于 2012-09-25T17:32:50.987 回答
0

编写一个包装方法,String如下所示

map.put(string.toLowerCase());

并获取方法

map.get(string.toLowerCase());
于 2012-09-25T17:21:44.173 回答