Java 集合<字符串>平等忽略大小写

2022-01-17 00:00:00 set java ignore-case

我想通过忽略字母的大小写来检查两组字符串的所有元素是否相等.

I want to check if all elements of two sets of String are equal by ignoring the letter's cases.

Set<String> set1 ;
Set<String> set2 ;
.
.
.
if(set1.equals(set2)){ //all elements of set1 are equal to set2 
 //dosomething
}
else{
 //do something else
}

但是,这种相等性检查不会忽略字符串的大小写.还有其他方法吗?

However, this equality check doesn't ignore the cases of the string. Is there some other way of doing that?

推荐答案

你也可以使用TreeSet.

public static void main(String[] args){
    Set<String> s1 = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    s1.addAll(Arrays.asList(new String[] {"a", "b", "c"}));

    Set<String> s2 = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
    s2.addAll(Arrays.asList(new String[] {"A", "B", "C"}));

    System.out.println(s1.equals(s2));
}

相关文章