Guest User

Untitled

a guest
Dec 12th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. import java.util.function.Consumer;
  2. import java.util.function.Function;
  3. import java.util.Optional;
  4.  
  5. public class Example {
  6.  
  7. public static void main(String []args) {
  8.  
  9. // Create a series of nullable objects.
  10. Test a = new Test();
  11. Test b = new Test();
  12. Test c = new Test();
  13. Test d = new Test();
  14.  
  15. a.setInner(b);
  16. b.setInner(c);
  17. c.setInner(d);
  18.  
  19. // This is probably as close as we're going to get to
  20. // null coalescing without actual language support.
  21. Optional
  22. .ofNullable(a)
  23. .map(i -> i.getInner())
  24. .map(i -> i.getInner())
  25. .map(i -> i.getInner())
  26. .ifPresent(i -> i.hello());
  27.  
  28. // If you go too deep and find a `null`, nothing happens.
  29. Optional
  30. .ofNullable(a)
  31. .map(i -> i.getInner())
  32. .map(i -> i.getInner())
  33. .map(i -> i.getInner())
  34. .map(i -> i.getInner())
  35. .map(i -> i.getInner())
  36. .map(i -> i.getInner())
  37. .ifPresent(i -> i.hello());
  38.  
  39. // You can also just retrieve a value instead of consuming the object.
  40. String string = Optional
  41. .ofNullable(a)
  42. .map(i -> i.getInner())
  43. .map(i -> i.getInner())
  44. .map(i -> i.getInner())
  45. .map(i -> i.toString())
  46. .orElse("<is null>");
  47.  
  48. System.out.println(string);
  49. }
  50.  
  51. private static class Test {
  52. private Test inner;
  53.  
  54. public Test getInner() {
  55. return inner;
  56. }
  57.  
  58. public void hello() {
  59. System.out.println("Hello, world!");
  60. }
  61.  
  62. public void setInner(Test inner) {
  63. this.inner = inner;
  64. }
  65. }
  66. }
Add Comment
Please, Sign In to add comment