Storing lambdas as values in a Map turns a chain of if-else branches into a lookup: choosing which behavior to run becomes choosing which key to fetch, which scales cleanly as more strategies are added.
Map<String, Runnable> actions = new LinkedHashMap<>();
actions.put("start", () -> System.out.println("Starting the engine"));
actions.put("stop", () -> System.out.println("Stopping the engine"));
for (String command : List.of("start", "stop")) {
actions.getOrDefault(command, () -> System.out.println("Unknown command")).run();
}
Starting the engine
Stopping the engine
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27