在HashMap中自定义get方法 [英] Customizing the get method in HashMap

查看:105
本文介绍了在HashMap中自定义get方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

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

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

I have a Hashmap with a String as the key and an integer as the value. Now, I am using the get method to get the values, where the string matches with the key value.

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

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






我希望此字符串比较不区分大小写。无论如何我能做到吗?


I want this string comparison to be case insensitive. Is there anyway I can do that ?

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

For example, I want it to return the same result in the following cases:

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


推荐答案

如果性能不重要,可以使用< a href =http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html =nofollow> TreeMap 。输出以下代码:

If performance is not critical, you can use a TreeMap. Output of the code below:


1

6

6

1
6
6

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

Note that the behaviour you require is not compliant with Map#get contract:


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

More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)



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"));
}

这篇关于在HashMap中自定义get方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆