Lambda Expressions
With Java 8, functional programming was introduced to Java. Lambda expressions can be seen as a way to implement anonymous functions. They allow passing behavior as a code block.
Syntax
(parameters) -> expression
(parameters) -> { statements; }
Examples
() -> System.out.println(1);
x -> System.out.println(x);
() -> {
System.out.println(1);
System.out.println(2);
};
(a, b) -> a + b;
(Long m, Long n) -> m + n;
Functional Interfaces
- An interface that contains exactly one abstract method.
- Java provides the
@FunctionalInterfaceannotation to help enforce this rule during compilation, though it's not strictly required. - The abstract method in the interface defines the signature that a lambda expression must follow, known as the function descriptor.
Commonly Used Functional Interfaces
| Interface | Parameters | Return Type | Purpose |
|---|---|---|---|
| Predicate<T> | T | boolean | Evalautes a condition on an object |
| Consumer<T> | T | void | Performs an operation with an object but returns nothing |
| Function<T, R> | T | R | Transforms an input of one type to an output of another type |
| Supplier<T> | None | T | Provides an object of the given type |
| UnaryOperator<T> | T | T | Operates on a single object and returns the same type |
| BiFunction<T, U, R> | (T, U) | R | Accepts two inputs and returns a result |
| BinaryOperator<T> | (T, T) | T | Operates on two objects of the same type and returns the same type |
There are also primitive-specialized functional interfaces like IntFunction, which help avoid autoboxing and improve performance.
Method References
Method references are a shorthand syntax for lambda expressions that call existing methods. They allow reusing method definitions and passing them as lambda expressions.
Types of Method References
Reference to a Static Method
// Lambda expression
(args) -> ClassName.staticMethod(args);
// Method reference
ClassName::staticMethod;
Reference to an Instance Method of an Arbitrary Object
// Lambda expression
(args) -> args.instanceMethod();
// Method reference
ClassName::instanceMethod;
Reference to an Instance Method of a Specific Object
// Lambda expression
(args) -> object.instanceMethod(args);
// Method reference
object::instanceMethod;
Examples
// Static method reference
Consumer<string> parseString = Integer::parseInt;
// Instance method reference (on arbitrary object)
Consumer<string> getStringLength = String::length;
// Instance method reference (on specific object)
StringBuilder builder = new StringBuilder();
Consumer<string> appendToBuilder = builder::append;</string></string></string>