Java Set equality ignore case

前端 未结 6 1476
渐次进展
渐次进展 2020-12-11 00:14

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         


        
6条回答
  •  -上瘾入骨i
    2020-12-11 00:43

    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
    }
    

提交回复
热议问题