I want to check if all elements of two sets of String are equal by ignoring the letter\'s cases.
Set set1 ;
Set set2 ;
.
.
.
if(s
Unfortunately, Java does not let you supply an external "equality comparer": when you use strings, HashSet
uses only built-in hashCode
and equals
.
You can work around this problem by populating an auxiliary HashSet
with strings converted to a specific (i.e. upper or lower) case, and then checking the equality on it, like this:
boolean eq = set1.size() == set2.size();
if (eq) {
Set aux = new HashSet();
for (String s : set1) {
aux.add(s.toUpperCase());
}
for (String s : set2) {
if (!aux.contains(s.toUpperCase())) {
eq = false;
break;
}
}
}
if (eq) {
// The sets are equal ignoring the case
}