在HashMap中自定义get方法
可能重复:
不区分大小写的字符串作为HashMap键
我有一个Hashmap,其中一个String作为键,一个整数作为值。 现在,我使用get方法获取值,其中字符串与键值匹配。
HashMap map= new HashMap(); // Populate the map System.out.println(map.get("mystring"));
我希望这个字符串比较不区分大小写。 无论如何我能做到吗?
例如,我希望它在以下情况下返回相同的结果:
map.get("hello"); map.get("HELLO"); map.get("Hello");
如果性能不重要,则可以使用TreeMap 。 输出以下代码:
1
6
6
请注意,您需要的行为不符合Map#get
contract :
更正式地说,如果此映射包含从键k到值v的映射,使得(key == null?k == null:key.equals(k)),则此方法返回v; 否则返回null。 (最多可以有一个这样的映射。)
public static void main(String[] args) { Map 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")); }
你可以做
Map map= new HashMap() { @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()); } };
您可以创建一个包装类,它将包装HashMap并实现get和put方法。
HashMap 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
编写一个包装器方法,将String
放在下面
map.put(string.toLowerCase());
并获得方法
map.get(string.toLowerCase());