Search code examples
javasetignore-case

Java Set<String> equality 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?


Solution

  • Alternatively you can use 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));
    }