不区分大小写的字符串作为 HashMap 键 [英] Case insensitive string as HashMap key

查看:37
本文介绍了不区分大小写的字符串作为 HashMap 键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use case insensitive string as a HashMap key for the following reasons.

  • 在初始化期间,我的程序使用用户定义的字符串创建 HashMap
  • 在处理事件(在我的情况下是网络流量)时,我可能会在不同的情况下收到 String,但我应该能够从 HashMap 中找到 而忽略这种情况从流量中收到.
  • During initialization, my program creates HashMap with user defined String
  • While processing an event (network traffic in my case), I might received String in a different case but I should be able to locate the <key, value> from HashMap ignoring the case I received from traffic.

我遵循了这种方法

CaseInsensitiveString.java

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

LookupCode.java

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

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

Because of this, I'm creating a new object of CaseInsensitiveString for every event. So, it might hit performance.

有没有其他方法可以解决这个问题?

Is there any other way to solve this issue?

推荐答案

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

这正是您所需要的.

这篇关于不区分大小写的字符串作为 HashMap 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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