fork download
  1. import java.util.Optional;
  2.  
  3. public final class Main {
  4.  
  5. public static void main (String[] args) {
  6. var yellow = Color.findByName("YELLOW");
  7. yellow.ifPresent(c -> {
  8. var rgb = c.getRgb();
  9. System.out.println("yellow: rgb=" + rgb);
  10. });
  11.  
  12. // Alternatively, we may write as follows, but...
  13. var blue = Color.findByName("BLUE");
  14. if (blue.isPresent()) {
  15. var rgb = blue.get().getRgb();
  16. System.out.println("blue: rgb=" + rgb);
  17. }
  18. }
  19.  
  20. public interface Color {
  21.  
  22. /** Represents blue. */
  23. static final Color BLUE = () -> 0xff;
  24.  
  25. /**
  26. Returns the Color instance that matches with the specified name.
  27.  
  28. @param name
  29. ...
  30. @return
  31. An {@link Optional<T> Optional} object containing the Color
  32. instance that matches with {@code name}, or an empty Optional
  33. object (if nothing matches).
  34. */
  35. static Optional<Color> findByName(String name) {
  36. return name.equals("BLUE")
  37. ? Optional.of(Color.BLUE)
  38. : Optional.empty();
  39. }
  40.  
  41. /**
  42. Returns the 24-bit integer value representing RGB.
  43.  
  44.   @return
  45.   ...
  46.   */
  47. int getRgb();
  48. }
  49. }
  50.  
Success #stdin #stdout 0.11s 34156KB
stdin
Standard input is empty
stdout
blue: rgb=255