Guest User

Untitled

a guest
Apr 25th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. public class OptionalChainingComposed {
  2.  
  3. public static void main(String[] args) {
  4. OptionalChainingComposed optionalChaining = new OptionalChainingComposed();
  5. optionalChaining.happyPath();
  6. optionalChaining.nullInput();
  7. }
  8.  
  9. public void happyPath() {
  10. nonNullPipeline("happyPath")
  11. .ifPresent(System.out::println);
  12. }
  13.  
  14. public void nullInput() {
  15. nonNullPipeline(null).ifPresent(val -> val.concat("boom!"));
  16. }
  17.  
  18.  
  19. // Instead of THIS:
  20. // public Optional<String> nonNullPipeline(String string) {
  21. // return Optional.ofNullable(stringOptional)
  22. // .map(val -> operation1.apply(val))
  23. // .map(val -> operation2.apply(val))
  24. // .map(val -> operation3.apply(val));
  25. // }
  26.  
  27. // put these here so we don't get an illegal forward reference...
  28. Function<String, String> operation1 = String::toLowerCase;
  29. Function<String, String> operation2 = String::toUpperCase;
  30. Function<String, String> operation3 = value -> value.concat("suffix");
  31. Function<String, String> operation4 = value -> null;
  32.  
  33. // We can do THIS:
  34. Function<String, String> pipelineOne = operation1.andThen(operation2).andThen(operation3);
  35.  
  36. // And this:
  37. public Optional<String> nonNullPipeline(String string) {
  38. return Optional.ofNullable(string).map(pipelineOne);
  39. }
  40.  
  41. }
Add Comment
Please, Sign In to add comment