fork download
  1. import java.util.HashMap;
  2. import java.util.Map;
  3.  
  4. public final class Main {
  5.  
  6. private static final Runnable DO_NOTHING = () -> {};
  7.  
  8. private final Map<Character, Runnable> map;
  9.  
  10. public Main() {
  11. map = new HashMap<>();
  12. map.put('h', () -> moveCursorLeft());
  13. map.put('j', () -> moveCursorUp());
  14. map.put('k', () -> moveCursorDown());
  15. map.put('l', () -> moveCursorRight());
  16. }
  17.  
  18. private void handleKeyInput() {
  19. var c = getPressedKey();
  20. // Of course, you can pass the method reference to an empty method
  21. // instead of 'DO_NOTHING'.
  22. var action = map.getOrDefault(c, DO_NOTHING);
  23. action.run();
  24. // In fact, you don't need 'action' and can write:
  25. //
  26. // map.getOrDefault(c, DO_NOTHING)
  27. // .run();
  28. }
  29.  
  30. /**
  31.   Returns the character of the pressed key.
  32.   If no key is pressed, blocks until any key is pressed.
  33.  
  34.   @return
  35.   The character of the pressed key.
  36.   */
  37. private char getPressedKey() {
  38. return 'a';
  39. }
  40.  
  41. private void moveCursorRight() {}
  42. private void moveCursorUp() {}
  43. private void moveCursorDown() {}
  44. private void moveCursorLeft() {}
  45.  
  46. public static void main(String[] args) {
  47. var m = new Main();
  48. m.handleKeyInput();
  49. }
  50. }
  51.  
Success #stdin #stdout 0.09s 33660KB
stdin
Standard input is empty
stdout
Standard output is empty