Java:不区分大小写的映射键,其中键为 Pair<String, String>

问题描述 投票:0回答:1

我有 Java 地图:

 Map<Pair<String, String>, MyClass> myMap;

我需要配对区分大小写。 常规字符串键的解决方案很简单:

 TreeMap<String, MyClass> myMap= new TreeMap(String.CASE_INSENSITIVE_ORDER);

但是,字符串对键的情况怎么样?

java compare key-value case-insensitive
1个回答
0
投票

如果你想使用

TreeMap
(如果你需要排序),你可以编写一个自定义的
Comparator
,如评论中提到的

但是,您也可以使用

hashCode
equals
方法创建自定义键类,并使用
HashMap
:

record CaseInsensitiveStringPair(String first, String second){
    @Override
    public boolean equals(Object other){
        return other instanceof CaseInsensitiveStringPair o &&
            first().equalsIgboreCase(o.first()) &&
            second().equalsIgboreCase(o.second()) 
    }
    @Override
    public int hashCode(){
        return Objects.hash(first(), second());
    }
}

然后使用

Map<CaseInsensitiveStringPair, MyClass map = new HashMap<>();
© www.soinside.com 2019 - 2024. All rights reserved.