String.equals() with multiple conditions (and one action on result) [duplicate]
Solution 1:
Possibilities:
-
Use
String.equals()
:if (some_string.equals("john") || some_string.equals("mary") || some_string.equals("peter")) { }
-
Use a regular expression:
if (some_string.matches("john|mary|peter")) { }
-
Store a list of strings to be matched against in a Collection and search the collection:
Set<String> names = new HashSet<String>(); names.add("john"); names.add("mary"); names.add("peter"); if (names.contains(some_string)) { }
Solution 2:
if (Arrays.asList("John", "Mary", "Peter").contains(name)) {
}
- This is not as fast as using a prepared Set, but it performs no worse than using OR.
- This doesn't crash when name is NULL (same with Set).
- I like it because it looks clean
Solution 3:
Keep the acceptable values in a HashSet
and check if your string exists using the contains method:
Set<String> accept = new HashSet<String>(Arrays.asList(new String[] {"john", "mary", "peter"}));
if (accept.contains(some_string)) {
//...
}
Solution 4:
Your current implementation is correct. The suggested is not possible but the pseudo code would be implemented with multiple equal()
calls and ||
.
Solution 5:
If you develop for Android KitKat or newer, you could also use a switch statement (see: Android coding with switch (String)). e.g.
switch(yourString)
{
case "john":
//do something for john
case "mary":
//do something for mary
}