fork download
  1. import java.util.List;
  2. import java.util.Map;
  3. import java.util.Optional;
  4. import java.util.stream.Collectors;
  5. import static java.util.Map.entry;
  6.  
  7. public final class Main {
  8.  
  9. private static final Map<String, Runnable> COMMAND_MAP = Map.ofEntries(
  10. entry("help", () -> printHelp()),
  11. entry("quit", () -> exitProgram()),
  12. entry("shutdown", () -> shutdownSystem()));
  13.  
  14. private static void printHelp() {
  15. System.out.println("printHelp");
  16. }
  17.  
  18. private static void exitProgram() {
  19. System.out.println("exitProgram");
  20. }
  21.  
  22. private static void shutdownSystem() {
  23. System.out.println("shutdownSystem");
  24. }
  25.  
  26. private static List<String> getCommandList() {
  27. return List.of("help", "reboot", "shutdown");
  28. }
  29.  
  30. private static void fixMe() {
  31. var list = getCommandList().stream()
  32. .flatMap(n -> Optional.ofNullable(COMMAND_MAP.get(n)).stream())
  33. .collect(Collectors.toList());
  34.  
  35. // The next is also fine, but the number of elements differs:
  36. //
  37. // var list = getCommandList().stream()
  38. // .map(n -> COMMAND_MAP.getOrDefault(n, () -> {}))
  39. // .collect(Collectors.toList());
  40.  
  41. list.forEach(r -> r.run());
  42. }
  43.  
  44. public static void main(String[] args) {
  45. fixMe();
  46. }
  47. }
  48.  
Success #stdin #stdout 0.08s 34372KB
stdin
Standard input is empty
stdout
printHelp
shutdownSystem