The are many solutions suggested and most are working solutions. However i must add here that people suggesting using regex i.e str.matches("val1|val2|val3")
is okay however
I would suggest to use apache commons lang3 stringUtils StringUtils.equalsAny(str, "val1", "val2", "val3")
instead
Test:
public static void main(String[] args) {
String var = "val1";
long t, t1 = 0, t2 = 0;
for (int i = 0; i < 1000; i++) {
t = System.currentTimeMillis();
var.matches("val1|val2|val3");
t1 += System.currentTimeMillis() - t;
t = System.currentTimeMillis();
StringUtils.equalsAny(var, "val1", "val2", "val3");
t2 += System.currentTimeMillis() - t;
}
System.out.println("Matches took + " + t1 + " ms\nStringUtils took " + t2 + " ms");
}
Results after 1000 iteration:
Matches took + 18 ms
StringUtils took 7 ms