Java 8 - Part III [Lambda]
Hey, let's continue the Java 8 series!!!
This post is the third subject about the changes that you can find between version 6 to 8. Here I will talk about the Lambda.
Summary
So... what is the Lambda expression?
It's a new concept of function as the value. The lambda expression is used in many languages that follow the Functional Programming paradigm. It is an anonymous function. Java is able, for example, to store a method in a variable and pass a method as a parameter. In other words: behaviour parameterization. A big advantage is a concise representation.
It is an anonymous function that allows you to pass methods as arguments or simply, a mechanism that helps you remove a lot of boilerplate code.
The syntax:
- parameters + arrow + body: (args1, args2, args3, ……) -> { body }
- Parameter:
- Quantity: zero or more
- Zero: () -> System.out.println("Hi");
- One parameter: the parentheses is not mandatory
- s -> System.out.println(s);
- Type: can be declared explicitly, or it can be inferred from the context
- (s) -> System.out.println(s);
- (String s) -> System.out.println(s);
- Quantity: zero or more
- Body
- Quantity: one or more statements
- One statement: curly brackets are not required
- Return:
- it is optional if the body doesn't return a result.
- If the
return
keyword is used, curly brackets are required.
Lambda Expression vs Anonymous Inner Class
Lambda | Anonymous |
---|---|
Lambda
- It implements a functional interface
- Lambdas can only access final or effectively final variable
- It is not a scope of its own but is part of the enclosing scope. Lambda can access instance or static variables of the enclosing class.
- It is an
invokedynamic
instruction. This allows dynamic languages to bind to symbols at runtime.- Lambda is compiled and converted into a private method of the class.
- Performance: it is pure compile-time activity and doesn’t incur extra cost during runtime.
Anonymous Inner Class
- It can extend a class or implement an interface with any number of methods
- It can use instance variables and thus can have state
- it has scope for variable defined inside the inner class (it's a class).
- It compiles to a class
- Performance: It requires class loading, memory allocation, object initialization and invocation of a non-static method. So lambda has better performance than anonymous inner classes.
PS> These differences were completely extracted from [1] [2]
Tips
- Lambda can only throw the same type or a subtype checked exceptions specified in the throws clause of the functional interface method.
- Lambda cannot access the default methods of a functional interface.
- It does not allow passing a constant value as a parameter.
- If
this
is used in the lambda, it refers to the enclosing class where the expression is written. - The type of a lambda is deduced from the context
- Lambda expressions can be used in:
- A variable declaration
- An assignment
- A return statement
- An array initializer
- As a method or constructor arguments
- A ternary conditional expression
- A cast expression
Reference: Java In Action (GitHub) - No Lambda
Reference: Java In Action (GitHub) - Using Lambda
Use it if you …
- "are encapsulating a single unit of behavior that you want to pass to other code."
- "need a simple instance of a functional interface and none of the preceding criteria apply".
Functional Interface
It is an interface that specifies only one abstract method and zero or more default methods. Comparator and Runnable are examples of functional interfaces because the first one has only compare method and the second one the run method. The lambda expression can be considered an instance of the concrete implementation of the functional interface.
- The @FunctionalInterface annotation can be used to identify a functional interface. It is optional, however, it is a good practice. If the annotation is used and the interface is not a valid functional interface, it will generate a compile-time error.
- Function descriptor identify the signature of the abstract method of a functional interface.
- Java library has new functional interfaces inside the java.util.function package (Predicate, Consumer, Function, Supplier, UnaryOperator, BinaryOperator, BiPredicate, BiConsumer, BiFunction).
Java Built-in Lambda Interface
This interface was created to cover the most common scenarios usages. The letters T
and U
represent parameter types and R
the return type.
Functional Interface: Supplier
Functional Interface: Predicate
Functional Interface: BiPredicate<L, R>; Function Descriptor: (L,R) -> boolean
Functional Interface: Consumer
Functional Interface: BiConsumer<T, U>; Function Descriptor: (T, U) -> void
Functional Interface: Function<T, R>; Function Descriptor: T -> R
Functional Interface: UnaryOperator
Functional Interface: BiFunction<T, U, R>; Function Descriptor: (T, U) -> R
Functional Interface: BinaryOperator
The complete code examples you can see in “Java In Action” github - Lambda and OCP8 - Lambda Expression.
Return Optional
The type Option was created to represent concepts like "not knowing" or "not applicable". It can be empty or it can have some value. It will help a lot the old problems with null value. Optional is a clear statement and allow the use of functional programming style.
Optional example you can find in github/fabiana2611
Method Reference
It is similar to lambda, but it can be clearer. You can use this using (1) Class::staticMethod with no arguments (If exists arguments it is passed automatically behind the curtain); (2) with an instance method of an existent object; and (3) with the constructor. Good complete examples you can see in JavaInAction and OCP8.
Related Posts
- Java 8 - Part VII [Collections]
- Java 8 – Part VI [File IO NIO.2]
- Java 8 – Part V [Concurreny]
- Java 8 – Part IV [Streams]
- Java 8 – Parte III [Lambda]
- Java 8 - Part II [Localization, Date, Time]
- Java 8 - Language Enhancements
- JVM
References
- Lambda Expression Explained in 5 minutes
- OCP8: Lambda Expression
- OCP8: Method Reference
- StackOverflow: Advantages of lambda
- Java Tutorials: Lambda Expression
- Java In Action
- Java In Action - Github
- Lambda vs Anonymous Inner class: [1] [2]
- Java Lambda - IntToLongFunction example