出于以下原因,我想使用不区分大小写的字符串作为HashMap键。

在初始化过程中,我的程序用用户定义的字符串创建HashMap 在处理事件(在我的情况下是网络流量)时,我可能会在不同的情况下收到字符串,但我应该能够定位<键,值>从HashMap忽略我从流量收到的情况。

我采用了这种方法

CaseInsensitiveString.java

    public final class CaseInsensitiveString {
            private String s;

            public CaseInsensitiveString(String s) {
                            if (s == null)
                            throw new NullPointerException();
                            this.s = s;
            }

            public boolean equals(Object o) {
                            return o instanceof CaseInsensitiveString &&
                            ((CaseInsensitiveString)o).s.equalsIgnoreCase(s);
            }

            private volatile int hashCode = 0;

            public int hashCode() {
                            if (hashCode == 0)
                            hashCode = s.toUpperCase().hashCode();

                            return hashCode;
            }

            public String toString() {
                            return s;
            }
    }

LookupCode.java

    node = nodeMap.get(new CaseInsensitiveString(stringFromEvent.toString()));

因此,我为每个事件创建了CaseInsensitiveString的新对象。因此,它可能会影响性能。

有没有其他办法解决这个问题?


当前回答

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

这就是你所需要的。

其他回答

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

这就是你所需要的。

正如Guido García在他们的回答中所建议的:

import java.util.HashMap;

public class CaseInsensitiveMap extends HashMap<String, String> {

    @Override
    public String put(String key, String value) {
       return super.put(key.toLowerCase(), value);
    }

    // not @Override because that would require the key parameter to be of type Object
    public String get(String key) {
       return super.get(key.toLowerCase());
    }
}

Or

https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/CaseInsensitiveMap.html

我喜欢使用ICU4J的CaseInsensitiveString包装Map键,因为它照顾哈希\等于和问题,它适用于unicode\i18n。

HashMap<CaseInsensitiveString, String> caseInsensitiveMap = new HashMap<>();
caseInsensitiveMap.put("tschüß", "bye");
caseInsensitiveMap.containsKey("TSCHÜSS"); # true

一种方法是创建Apache Commons AbstractHashedMap类的自定义子类,覆盖散列和isEqualKeys方法来执行不区分大小写的散列和键的比较。(注:我自己从来没有试过……)

这避免了每次需要执行映射查找或更新时创建新对象的开销。常见的Map操作应该是O(1)…就像一个普通的HashMap。

如果您准备接受他们所做的实现选择,Apache Commons CaseInsensitiveMap将为您定制/专门化AbstractHashedMap。


但是如果O(logN)获取和放置操作是可接受的,那么带有不区分大小写字符串比较器的TreeMap是一个选项;例如,使用String.CASE_INSENSITIVE_ORDER。

如果您不介意每次执行put或get操作时创建一个新的临时String对象,那么Vishal的答案就很好。(不过,我注意到,如果你这样做,你就不会保留键的原始大小写…)

我想到了两个选择:

你可以直接使用s.toUpperCase().hashCode();作为地图的钥匙。 你可以使用TreeMap<String>和一个忽略大小写的自定义比较器。

否则,如果您更喜欢自己的解决方案,我宁愿不定义一种新的String,而是实现一个具有所需的大小写不敏感功能的新Map。