4

I'm trying to test whether a set of strings contains a particular string, independent of case. For example, if mySet contained "john" xor "John" xor "JOHN" xor..., then

mySet.contains("john")

(or something similar) should return true.

djlovesupr3me
  • 79
  • 2
  • 8
  • 1
    Similar question: [ArrayList contains case sensitivity](http://stackoverflow.com/q/8751455/142162) –  Mar 03 '14 at 21:41
  • I mean, the answer is: you can't if you're using `.contains()`. Sets use hashing. You'd have to iterate through the set and compare each entry. – Brian Roach Mar 03 '14 at 21:46
  • @BrianRoach, right, simply using `contains()` doesn't work. I'm looking for something that has similar behavior as that method, but case insensitive. – djlovesupr3me Mar 03 '14 at 21:58

1 Answers1

13

When constructing the set, use a sorted set with a case insensitive comparator. For example:

Set<String> s = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
s.addAll(Arrays.asList("one", "two", "three"));

//Returns true
System.out.println("Result: " + s.contains("One"));
prunge
  • 22,460
  • 3
  • 73
  • 80