djlovesupr3me
djlovesupr3me

Reputation: 79

Check if a Java Set contains a particular string, independent of case

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.

Upvotes: 4

Views: 5609

Answers (1)

prunge
prunge

Reputation: 23248

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"));

Upvotes: 13

Related Questions