Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Hanoi JUG: Java 8 & lambdas

2,300 views

Published on

Presentation of Lambda in Java 8 for the Hanoi Java User Group on Thursday, April 16, 2015

http://www.meetup.com/Hanoi-Java-User-Group/events/220963110/

Published in: Technology

Hanoi JUG: Java 8 & lambdas

  1. 1. Hanoi JUG - 2015 Java 8: Lambdas Benoît de CHATEAUVIEUX - eXo
  2. 2. Hanoi JUG - 2015 Simple poll ! Who knows Java ? Who knows Lambda ? Who knows Functional Programming ?
  3. 3. Hanoi JUG - 2015 Why talking about Java 8 today ? Java 7 End Of Public Updates = April 2015 https://plumbr.eu/blog/java/java-version-statistics-2015-edition
  4. 4. Hanoi JUG - 2015 What’s new in Java 8 ? Java 8 (March 18, 2014): ● JEP 126: Lambda & Stream ● JEP 174: Project Nashorn (JS in Java) ● JEP 104: Annotation on Java Types ● Unsigned Integer Arithmetic ● JEP 120: Repeating annotations ● JEP 150: Date and Time API ● JEP 178: Statically-linked JNI libraries ● JEP 153: Launch JavaFX applications ● JEP 122: Remove the permanent generation JEP = JDK Enhancement Proposals
  5. 5. Hanoi JUG - 2015 Agenda AGENDA 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  6. 6. Hanoi JUG - 2015 Lambda in Java Lambda expressions is the single largest upgrade to the programming model ever - larger even than generics. This is the first time we have done a carefully coordinated co-evolution of the JVM, the language, and the libraries all together – and the results still feel like Java. Mark Reinhold “Chief Architect of the Java Platform” https://blogs.oracle.com/java/entry/the_javaone_2013_technical_keynote
  7. 7. Hanoi JUG - 2015 So, what is lambda ? Lambda comes from the Functional Programming: - Lambda Calcul by Alonzo Church in 1936 - Lisp by John McCarthy in 1958 - …. Functional Programming 1. Everything is a (mathematical) function a. Pure functions (compute output from input → no side effect) b. First-class and higher-order functions. i.e. function that i. takes one or more functions as an input ii. or outputs a function 2. Immutability 3. Recursion (no loop but functions that call themselves) 4. Lambda (anonymous functions) Programming Imperative Declarative Procedural (ex: Fortran, C) Object Oriented (ex: Java, C++) Logic (ex: Prolog) Functional (ex: Haskell, Erlang)
  8. 8. Hanoi JUG - 2015 So, what is lambda ? For us Lambda == a piece of functionality I will not detail Functional Programming in this presentation Hey ! Opportunity for a future JUG meeting ! Any speaker ?
  9. 9. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  10. 10. Hanoi JUG - 2015 Syntax Without lambda new SomeInterface() { @Override public SomeType someMethod(OtherType args) { … body ... return result; } } Lambda (OtherType args) -> { … body … return result; } Boilerplate code
  11. 11. Hanoi JUG - 2015 Example #1 : Runnable
  12. 12. Hanoi JUG - 2015 Example #2 : Comparator
  13. 13. Hanoi JUG - 2015
  14. 14. Hanoi JUG - 2015 Type inferencing Types in argument list can be omitted. Since there is only one method in the functional interface, the compiler knows the expected types of the params Basic lambda (String firstName, String lastName) -> { return firstName + “ “ + lastName } Lambda with type infering (firstName, lastName) -> { return firstName + “ “ + lastName }
  15. 15. Hanoi JUG - 2015 Implied return value For body, if expression is used instead of block, this expression will be returned with no explicit “return” needed If method is void, no value is returned Basic lambda (firstName, lastName) -> { return firstName + “ “ + lastName } Lambda with implied return value (firstName, lastName) -> { firstName + “ “ + lastName }
  16. 16. Hanoi JUG - 2015 Omitting parenthesis If method takes a single parameter, parenthesis are optional Basic lambda (firstName) -> { “First name: “ + firstName } Lambda with implied return value firstName -> { “First name: “ + firstName }
  17. 17. Hanoi JUG - 2015 Summary: lambda makes the code shorter Java 7 taskList.execute(new Runnable() { @Override public void run() { doSomething(arg); } }); Java 8 taskList.execute( () -> doSomething(arg) );
  18. 18. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  19. 19. Hanoi JUG - 2015 Definition A functional interface is a Java interface that lists only one method declaration. Previously, they were known as a Single Abstract Method type (SAM)
  20. 20. Hanoi JUG - 2015 @FunctionalInterface Interfaces are same in Java 7 and Java 8 Implementations of interfaces are also same in Java 7 and Java 8 Code that call functional interface can use lambda or not @FunctionalInterface is not required but expresses design intent Functional interfaces can be verified at compile time
  21. 21. Hanoi JUG - 2015 Reminder: Definition
  22. 22. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  23. 23. Hanoi JUG - 2015 Default & Static methods Functional interfaces have 1 single abstract method (this is the method that the lambda specifies) But interfaces in Java 8 can have default methods that ● have bodies ● are inherited They also can have static methods ⇒ They are more like abstract classes ⇒ We now have multiple inheritance of implementation in Java !
  24. 24. Hanoi JUG - 2015 Let’s code ! You can avoid writing your functional interface. Java 8 has Built-in functions in java.util. function package So, let’s code… If you want to code with lambda you have to 1. Write a functional interface (annotated or not with @FunctionalInterface) 2. Write a code that call this functional interface
  25. 25. Hanoi JUG - 2015 Java 8: Lambdas AGENDA 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  26. 26. Hanoi JUG - 2015 Built-in functions java.util.function package contains 43 general purpose functional interfaces. 4 families of functional interfaces Those functions can be ● Simply Typed ● Generic Function takes arguments and return something Predicate take arguments and return a boolean Consumer take arguments and return void Supplier take no argument and return something
  27. 27. Hanoi JUG - 2015 Simply Typed Building Blocks Functional interfaces are named according to arguments and return value. java.util.function package contains built-in functions for simples types (Boolean, Double, Int, Long). Some are ● Unary: one argument ● Binary: two arguments ex: IntPredicate (int in, boolean out) LongUnaryOperator(long in, long out) DoubleBinaryOperator(two doubles in, double out)
  28. 28. Hanoi JUG - 2015 Generic Building Blocks java.util.function package also contains generic built-in functions: ● Function ○ Function<T,R> : unary function from T to R ○ BiFunction<T, U, R> : binary function from T and U to R ○ DoubleFunction<R> : unary function from double to R ○ ... ● Predicate ○ Predicate<T> : unary function from T to boolean ○ ... ● Consumer ○ Consumer<T> : unary function from T to void ○ ... ● Supplier ○ Supplier<T> : unary function from void to T ○ ...
  29. 29. Hanoi JUG - 2015 Example: Predicate We’ll see in next presentation that getFirstMatchingActivity() can be written more elegantly with Stream
  30. 30. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  31. 31. Hanoi JUG - 2015 Composing functions Functional interfaces can be composed. Some examples: ● Function ○ Function<V, R> compose(Function<? super V, ? extends T> before) ○ Function<T, V> andThen(Function<? super R, ? extends V> after) ○ Returns a composed Function that applies functions in sequence ● Predicate ○ Predicate<T> negate() ○ Predicate<T> and(Predicate<? super T> other) ○ Predicate<T> or(Predicate<? super T> other) ○ Compose predicates using boolean logic ● Consumer ○ Consumer<T> andThen(Consumer<? super T> after) ○ Returns a composed Consumer that performs operations in sequence
  32. 32. Hanoi JUG - 2015 Composing lambda: Example
  33. 33. Hanoi JUG - 2015 Custom methods that return Lambdas Custom methods can also return lambda. The method can use a parameter to generate the lambda.
  34. 34. Hanoi JUG - 2015 Java 8: Lambdas AGENDA 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  35. 35. Hanoi JUG - 2015 Variable scoping Let’s go back to our Runnable implementations. Do you remember ? Those implementations are strictly equivalent….
  36. 36. Hanoi JUG - 2015 Variable scoping Well… not totally equivalent ! What happens if I introduce a local variable ? Lambda does not introduce a new level of scoping ● Lambda cannot introduce new variables with the same name as variables in method that creates the lambda ● “this” refers to the class the declare the lambda
  37. 37. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  38. 38. Hanoi JUG - 2015 Final vs Effectively final variables ● Lambda can only refer to local variable declared as final ● If a non-final local variable is never modified, the compiler consider it as “effectively final”
  39. 39. Hanoi JUG - 2015 Final vs Effectively final variables ● This limitation does not apply to instance variables
  40. 40. Hanoi JUG - 2015 Java 8: Lambdas 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  41. 41. Hanoi JUG - 2015 Method reference If the function we want to use already has a name, we don’t have to write a lambda for it: we can just use the method name: ● ClassName::staticMethodName ● variable::instanceMethodeName ● ClassName::new
  42. 42. Hanoi JUG - 2015 Java 8: Lambdas AGENDA 1. Basics a. Lambda b. Functional Interface c. Default & Static method 2. Built-in functions a. Built-in functions b. Composing functions 3. Lambda: Advanced a. Variable scoping b. Effectively final c. Method reference 4. Summary
  43. 43. Hanoi JUG - 2015 So… when to use lambda ? Use Case #1 Use it if you need a simple instance of a functional interface and you do not need a constructor, a named type, fields, or additional methods. Benefits ⇒ more concise, readable and succinct code ⇒ compatible with old Java 7 interfaces ⇒ shipped with prebuilt functional interfaces
  44. 44. Hanoi JUG - 2015 So… when to use lambda ? … but the syntax is not the most important thing about lambda.
  45. 45. Hanoi JUG - 2015 So… when to use lambda ? Use Case #2 Use it if you are encapsulating a single unit of behavior that you want to pass to other code. ○ For example, you would use a lambda expression if you want a certain action performed on each element of a collection, when a process is completed, or when a process encounters an error. Benefits ⇒ Start thinking in functions ⇒ avoid mutable states and thus locks ⇒ limit side-effects (and thus, bugs !) ⇒ design more composable and reusable API
  46. 46. Hanoi JUG - 2015 Paradigm shift The really fundamental thing about lambda expression is the huge paradigm shift they imply. … and learning a new language is relatively easy comparing to learning a new paradigm.
  47. 47. Hanoi JUG - 2015 Summary Java is now poly-paradigm. It’s getting functional. Let’s go for it !
  48. 48. Hanoi JUG - 2015 Further readings This presentation on Slideshare ● http://www.slideshare.net/benoitdechateauvieux/hanoi-jug-java-8-lambdas- 47013698 The code of this presentation ● https://github.com/benoitdechateauvieux/hanoi-jug-lambda Further readings ● https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html ● http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda- QuickStart/index.html ● http://www.slideshare.net/mariofusco/java-8-workshop ● http://www.beyondjava.net/blog/java-8-functional-programming-language/ ● http://www.infoq.com/articles/How-Functional-is-Java-8
  49. 49. Hanoi JUG - 2015 Questions ?

×