Lambda: a Map<String, Runnable> picks behavior like a strategy table

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.

Code
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();
}
Output
Starting the engine
Stopping the engine
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms