If you mean "most efficient" by "the best", read ahead.
I'm suggesting using the following method if there really is a lot.
String in Switch is actually something will be in Java 7. (As part of Project Coin)
And according to the proposal, this is the way Java language will implement it.
First, hash value of each of the strings is calculated. This problem is then a "switch int" problem, which is available in most currently language, and is efficient. In each of the case statement, you then check if this is really the string (in very rare cases different strings could hash to the same int).
I personally don't do the last step in practice sometimes as it's necessity depends on the situation you specific program is in, i.e. whether the strings possible are under the programmer's control and how robust the program need to be.
A sample pseudocode the corresponds
String s = ...
switch(s) {
case "quux":
processQuux(s);
// fall-through
case "foo":
case "bar":
processFooOrBar(s);
break;
case "baz":
processBaz(s);
// fall-through
default:
processDefault(s);
break;
}
from the fore-mentioned proposal to help you understand.
// Advanced example
{ // new scope for synthetic variables
boolean $take_default = false;
boolean $fallthrough = false;
$default_label: {
switch(s.hashCode()) { // cause NPE if s is null
case 3482567: // "quux".hashCode()
if (!s.equals("quux")) {
$take_default = true;
break $default_label;
}
processQuux(s);
$fallthrough = true;
case 101574: // "foo".hashCode()
if (!$fallthrough && !s.equals("foo")) {
$take_default = true;
break $default_label;
}
$fallthrough = true;
case 97299: // "bar".hashCode()
if (!$fallthrough && !s.equals("bar")) {
$take_default = true;
break $default_label;
}
processFooOrBar(s);
break;
case 97307: // "baz".hashCode()
if (!s.equals("baz")) {
$take_default = true;
break $default_label;
}
processBaz(s);
$fallthrough = true;
default:
$take_default = true;
break $default_label;
}
}
if($take_default)
processDefault(s);
}