Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 420
djlovesupr3me Avatar asked Dec 16 '22 00:12

djlovesupr3me


1 Answers

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"));
like image 134
prunge Avatar answered Jan 04 '23 22:01

prunge