You must have constants in your switch statement so what you specified won't work. You could do something like this though as an example. You're not limited to using Runnable
lambdas. Any functional Interface could be used and the appropriate arguments supplied when called.
Note that it is not a good idea to allow any
method of any
class to be invoked as it could lead to unexpected results or security issues depending on how it is to be used.
public class ThisClass {
public static void main(String[] args) {
Map<String, Runnable> map = new HashMap<>();
ThisClass tc = new ThisClass();
map.put("A", () -> tc.doOneThing());
map.put("B", () -> tc.doAnotherThing());
map.put("C", () -> tc.doAthirdThing());
map.put("D", () -> tc.doSomethingElse());
for (String str : new String[] { "A", "B", "Q", "C", "D", "E" }) {
map.getOrDefault(str, () -> tc.defaultMethod()).run();
}
}
public void doOneThing() {
System.out.println("Doing one thing");
}
public void defaultMethod() {
System.out.println("Executing default");
}
public void doAnotherThing() {
System.out.println("Doing Another thing");
}
public void doAthirdThing() {
System.out.println("Doing a third thing");
}
public void doSomethingElse() {
System.out.println("Doing something Else");
}
}
Prints
Doing one thing
Doing Another thing
Executing default
Doing a third thing
Doing something Else
Executing default
You can also do something like this.
Map<String, DoubleBinaryOperator> map = new HashMap<>();
map.put("+", (a, b) -> a + b);
map.put("-", (a, b) -> a - b);
map.put("*", (a, b) -> a * b);
map.put("/", (a, b) -> a / b);
DoubleBinaryOperator error = (a, b) -> {
throw new IllegalArgumentException();
};
for (String str : new String[] { "+", "-", "L", "/", "*" }) {
try {
double result = map.getOrDefault(str, error)
.applyAsDouble(2.0, 3.0);
System.out.println("result = " + result);
} catch (IllegalArgumentException iae) {
System.out.println("unknown operator \"" + str + "\"");
}
}
Prints
result = 5.0
result = -1.0
unknown operator "L"
result = 0.6666666666666666
result = 6.0