Functional java 8

1,685 views

Published on

A discussion of the new Java 8 features and how Java has become a functionalized programming language.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,685
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
89
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Functional java 8

  1. 1. Functional Java 8 This Ain’t Your Daddy’s JDK Nick Maiorano 1 ThoughtFlow Solutions Inc.
  2. 2. About me Developer Software Architect Independent Consultant ThoughtFlow Solutions Functional Java 8 – This Ain’t Your Daddy’s JDK 2
  3. 3. Available April 2014 Functional Java 8 – This Ain’t Your Daddy’s JDK 3
  4. 4. Functional Java 8 – This Ain’t Your Daddy’s JDK 4
  5. 5. What’s in Java 8? Encoding enhancements Encryption updates Functional libraries Concurrency Modularization Repeating annotations New Date/Time API Concurrency updates Java 8 Lambdas Nashorn JavaScript Engine Church Performance improvements Functional Java 8 – This Ain’t Your Daddy’s JDK GC updates Collections 5
  6. 6. What’s in Java 8? Functional libraries Concurrency Java 8 Lambdas Church Functional Java 8 – This Ain’t Your Daddy’s JDK Collections 6
  7. 7. The rocky road to lambdas • • • • • • Lambdas too difficult in late 1990s BGGA project initiated in 2007 JSR 335 filed in late 2009 Had to fit type system Maintain backward compatibility Java community divided Functional Java 8 – This Ain’t Your Daddy’s JDK 7
  8. 8. The rocky road to lambdas • • • • To be released as part of Java 7 To be released in September 2013 To be released in March 2014 Completing 7 years of work Functional Java 8 – This Ain’t Your Daddy’s JDK 8
  9. 9. Functional Programming • Rooted in lambda calculus • Hastened by death of Moore’s law • Programming paradigm of the times Functional Java 8 – This Ain’t Your Daddy’s JDK 9
  10. 10. Java DNA Structured Reflective Object Oriented Imperative Concurrent Generic Generic
  11. 11. Java DNA Structured Reflective Object Oriented Functional Imperative Concurrent Generic Generic
  12. 12. Organization Java Classes Vs. FP Functional Java 8 – This Ain’t Your Daddy’s JDK Functions 12
  13. 13. Building blocks Java Polymorphism, encapsulation, inheritance, dynamic binding Vs. FP Functional Java 8 – This Ain’t Your Daddy’s JDK Higher-order functions, currying, monads, list comprehensions 13
  14. 14. Algorithmic style Java Imperative: define behaviour as a series of steps Vs. FP Functional Java 8 – This Ain’t Your Daddy’s JDK Declarative: binding functions together without necessarily specifying their contents 14
  15. 15. State management Java Put state and behaviour together Vs. FP Functional Java 8 – This Ain’t Your Daddy’s JDK Avoid state 15
  16. 16. Mutability Java Supports mutability & immutability Vs. FP Functional Java 8 – This Ain’t Your Daddy’s JDK Emphasis on immutability 16
  17. 17. Design patterns Java Relies on design patterns to complement OOP for a higher level of abstraction Vs. FP Functional Java 8 – This Ain’t Your Daddy’s JDK Is already a higher level abstraction 17
  18. 18. Concurrency Java Use multi-threading, control access to shared resources via locks Vs. FP Functional Java 8 – This Ain’t Your Daddy’s JDK Organize processing into parallel workflows each dedicated to a core and avoid state, shared resources and locks 18
  19. 19. Recursion Java Supported with limitations Vs. FP Functional Java 8 – This Ain’t Your Daddy’s JDK Rudimentary 19
  20. 20. Expressiveness Java Clear & verbose Vs. FP Functional Java 8 – This Ain’t Your Daddy’s JDK Concise & dense 20
  21. 21. Functional Java “…Is a blend of imperative and object oriented programming enhanced with functional flavors” Functional Java 8 – This Ain’t Your Daddy’s JDK 21
  22. 22. Functional Java 8 – This Ain’t Your Daddy’s JDK 22
  23. 23. New Syntax • • • • Lambdas Functional interfaces Method references Default methods Functional Java 8 – This Ain’t Your Daddy’s JDK 23
  24. 24. What’s a lambda? Functional Java 8 – This Ain’t Your Daddy’s JDK 24
  25. 25. Anatomy of the lambda • Behavior-as-data facilitators • On-the-fly code definers • Ground-floor of FP Functional Java 8 – This Ain’t Your Daddy’s JDK 25
  26. 26. Anatomy of the lambda Lambda blocks (Parameter declaration) -> {Lambda body} (Integer i) -> {System.out.println(i);}; Functional Java 8 – This Ain’t Your Daddy’s JDK 26
  27. 27. Anatomy of the lambda Lambda blocks (Parameter declaration) -> {Lambda body} (Integer i) -> {System.out.println(i);}; Functional Java 8 – This Ain’t Your Daddy’s JDK 27
  28. 28. Anatomy of the lambda Lambda expressions Parameter name -> Lambda expression (Integer i) -> {System.out.println(i);}; Functional Java 8 – This Ain’t Your Daddy’s JDK 28
  29. 29. Anatomy of the lambda Lambda expressions Parameter name -> Lambda expression i -> System.out.println(i); Functional Java 8 – This Ain’t Your Daddy’s JDK 29
  30. 30. Anatomy of the lambda Lambda expressions Parameter name -> single statement; i -> i * 2; Functional Java 8 – This Ain’t Your Daddy’s JDK No return statement 30
  31. 31. Functional Interfaces • Lambdas are backed by interfaces • Single abstract methods • @FunctionalInterface Functional Java 8 – This Ain’t Your Daddy’s JDK 31
  32. 32. Functional Interfaces @FunctionalInterface public interface Calculator { int calculate(int x, int y); } Functional Java 8 – This Ain’t Your Daddy’s JDK 32
  33. 33. Functional Interfaces Calculator multiply = (x, y) -> x * y; Calculator divide = (x, y) -> x / y; int product = multiply.calculate(10, 20); int quotient = divide.calculate(10, 20); someMethod(multiply, divide); anotherMethod((x, y) -> x ^ y); Functional Java 8 – This Ain’t Your Daddy’s JDK 33
  34. 34. Functional Interfaces • Over 40 functional interfaces in JDK 8 • Rarely need to define your own • Generic and specialized Functional Java 8 – This Ain’t Your Daddy’s JDK 34
  35. 35. Functional Interfaces Consumer Supplier<T> T get() Supplier Functional Interfaces Consumer<T> void accept(T t); Function Function <T, R> R apply(T t); Predicate Predicate<T> boolean test(T t); Functional Java 8 – This Ain’t Your Daddy’s JDK 35
  36. 36. Method References Calculator maxFinder = (x, y) -> Math.max(x, y); Functional Java 8 – This Ain’t Your Daddy’s JDK 36
  37. 37. Method References Calculator maxFinder = Math::max; Math Calculator int max(int a, int b); int calculate(int x, int y); Functional Java 8 – This Ain’t Your Daddy’s JDK 37
  38. 38. Method References Type Template Static Class::method Instance instanceVariable::method Constructor Class::new Super super::method Generic constructor Class<Type>::new Array Class[]::new Functional Java 8 – This Ain’t Your Daddy’s JDK 38
  39. 39. Anonymous classes? • Do we still need anonymous classes? • Lambdas are behavior-only – no state • Only single abstract methods Functional Java 8 – This Ain’t Your Daddy’s JDK 39
  40. 40. Default Methods @FunctionalInterface public interface Calculator { int calculate(int x, int y); default int multiply(int x, int y) { return x * y; } } Functional Java 8 – This Ain’t Your Daddy’s JDK 40
  41. 41. Default Methods • Can be overloaded • Can be static or instance based • Introduce multiple inheritance Functional Java 8 – This Ain’t Your Daddy’s JDK 41
  42. 42. Functional Java 8 – This Ain’t Your Daddy’s JDK 42
  43. 43. Java-style functional programming • Other languages support FP natively • Java supports FP through libraries Functional interfaces Functional Java Streams Collections Functional Java 8 – This Ain’t Your Daddy’s JDK 43
  44. 44. Functionalized Collections Functional Java 8 – This Ain’t Your Daddy’s JDK 44
  45. 45. Functionalized Lists List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); stooges.forEach(s -> System.out.println(s); Functional Java 8 – This Ain’t Your Daddy’s JDK 45
  46. 46. Functionalized Lists List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); stooges.forEach(System.out::println); Functional Java 8 – This Ain’t Your Daddy’s JDK 46
  47. 47. Functionalized Lists Function<String, String> feminize = s -> "Larry".equals(s) ? "Lara" : "Moe".equals(s) ? "Maude" : "Shirley"; stooges.replaceAll(feminize); Functional Java 8 – This Ain’t Your Daddy’s JDK 47
  48. 48. Functionalized Lists Predicate<String> moeRemover = s -> “Moe".equals(s); stooges.removeIf(moeRemover); Functional Java 8 – This Ain’t Your Daddy’s JDK 48
  49. 49. Functionalized Maps Map<Integer, List<String>> movieDb = new HashMap<>(); movieDb.computeIfAbsent(1930, k -> new LinkedList<>()); movieDb.compute(1930, (k, v) -> { v.add(“Soup to nuts”); return v;}); Functional Java 8 – This Ain’t Your Daddy’s JDK 49
  50. 50. Functionalized Maps movieDb.putIfAbsent (1930, new LinkedList<>()); movieDb.getOrDefault (1930, new LinkedList<>()); Functional Java 8 – This Ain’t Your Daddy’s JDK 50
  51. 51. Streams Functional Java 8 – This Ain’t Your Daddy’s JDK 51
  52. 52. Streams Lambda Stream Operation 1 Functional Java 8 – This Ain’t Your Daddy’s JDK Lambda Operation 2 Lambda Operation 3 Lambda Operation 4 52
  53. 53. Streams Build Peek Filter Stream operations Iterate Map Reduce Functional Java 8 – This Ain’t Your Daddy’s JDK 53
  54. 54. Streams private static boolean isPerfect(long n) { long sum = 0; for (long i = 1; i <= n / 2; i++) { if (n % i == 0) { sum += i; } } return sum == n; } Functional Java 8 – This Ain’t Your Daddy’s JDK 54
  55. 55. Streams private static boolean isPerfect(long n) { return n > 0 && LongStream.rangeClosed(1, n / 2). filter(i -> n % i == 0). reduce(0, (l, r) -> l + r) == n; } Functional Java 8 – This Ain’t Your Daddy’s JDK 55
  56. 56. Streams • • • • Declarative constructs Can abstract any imperative for/while loop Work best when adhering to FP principles Easily parallelizable Functional Java 8 – This Ain’t Your Daddy’s JDK 56
  57. 57. Parallel Streams private static boolean isPerfect(long n) { return n > 0 && LongStream.rangeClosed(1, n / 2). filter(i -> n % i == 0). reduce(0, (l, r) -> l + r) == n; } Functional Java 8 – This Ain’t Your Daddy’s JDK 57
  58. 58. Parallel Streams private static boolean isPerfect(long n) { return n > 0 && LongStream.rangeClosed(1, n / 2). parallel(). filter(i -> n % i == 0). reduce(0, (l, r) -> l + r) == n; } Functional Java 8 – This Ain’t Your Daddy’s JDK 58
  59. 59. Parallel Streams Functional Java 8 – This Ain’t Your Daddy’s JDK 59
  60. 60. Parallel Streams Functional Java 8 – This Ain’t Your Daddy’s JDK 60
  61. 61. Parallel Streams • Uses fork-join used under the hood • Thread pool sized to # cores • Order can be changed Functional Java 8 – This Ain’t Your Daddy’s JDK 61
  62. 62. Parallel Streams private static boolean isPerfect(long n) { return n > 0 && LongStream.rangeClosed(1, n / 2). parallel(). filter(i -> n % i == 0). reduce(0, (l, r) -> l + r) == n; } Functional Java 8 – This Ain’t Your Daddy’s JDK 62
  63. 63. Parallel Streams private static boolean isPerfect(long n) { return n > 0 && LongStream.rangeClosed(1, n / 2). parallel(). filter(i -> n % i == 0). reduce(0, (l, r) -> l + r) == n; } List<Long> perfectNumbers = LongStream.rangeClosed(1, 8192). filter(PerfectNumberFinder::isPerfect). collect(ArrayList<Long>::new, ArrayList<Long>::add, ArrayList<Long>::addAll); Functional Java 8 – This Ain’t Your Daddy’s JDK 63
  64. 64. Parallel Streams private static boolean isPerfect(long n) { return n > 0 && LongStream.rangeClosed(1, n / 2). parallel(). filter(i -> n % i == 0). reduce(0, (l, r) -> l + r) == n; } List<Long> perfectNumbers = LongStream.rangeClosed(1, 8192).parallel(). filter(PerfectNumberFinder::isPerfect). collect(ArrayList<Long>::new, ArrayList<Long>::add, ArrayList<Long>::addAll); Functional Java 8 – This Ain’t Your Daddy’s JDK 64
  65. 65. Parallel Streams 8,128 33,550,336 8,589,869,056 137,438,691,328 Functional Java 8 – This Ain’t Your Daddy’s JDK Imperative 0 190 48648 778853 Serial Stream 1 229 59646 998776 Parallel Stream 0 66 13383 203651 65
  66. 66. Parallelization • Must avoid side-effects and mutating state • Problems must fit the associativity property • Ex: ((a * b) * c) = (a * (b * c)) • Must be enough parallelizable code • Performance not always better • Can’t modify local variables (unlike for loops) Functional Java 8 – This Ain’t Your Daddy’s JDK 66
  67. 67. Streams (the good) • • • • Allow abstraction of details Communicate intent clearly Concise On-demand parallelization Functional Java 8 – This Ain’t Your Daddy’s JDK 67
  68. 68. Streams (the bad) • • • • Loss of flexibility and control Increased code density Can be less efficient On-demand parallelization Functional Java 8 – This Ain’t Your Daddy’s JDK 68
  69. 69. Functional Java 8 – This Ain’t Your Daddy’s JDK 69
  70. 70. Final thoughts on Java 8 Functional Java 8 – This Ain’t Your Daddy’s JDK 70
  71. 71. How good is functional Java? • • • • • • Java now supports functional constructs But still OO at its core Functional expressions a little clunky Generics require more mental agility Conciseness is compromised Recursion not industrial strength Functional Java 8 – This Ain’t Your Daddy’s JDK 71
  72. 72. How good is functional Java? • FP integrated cohesively & coherently • New tools available for the masses Functional Java 8 – This Ain’t Your Daddy’s JDK 72
  73. 73. Available at Amazon April 2014 Functional Java 8 – This Ain’t Your Daddy’s JDK 73
  74. 74. @ThoughtFlow_Inc Functional Java 8 – This Ain’t Your Daddy’s JDK 74
  75. 75. Questions Functional Java 8 – This Ain’t Your Daddy’s JDK 75

×