Module lessons (1/2)
Lambda Expressions
Starting from Java 8, functional programming is supported via Lambda Expressions. A lambda expression is essentially an anonymous method (a function without a name) that can be passed as an argument to methods or stored in variables.
Functional Interfaces
A lambda expression can only be used where a Functional Interface is required. A functional interface is an interface that declares exactly one abstract method. Java marks these interfaces with the optional @FunctionalInterface annotation.
Example of a user-defined functional interface:
@FunctionalInterface
interface MathOperation {
int operate(int a, int b);
}
Before Java 8, you would have to define an anonymous inner class. With lambdas, the syntax is simplified to:
MathOperation addition = (a, b) -> a + b;
int result = addition.operate(5, 3); // Returns 8
Structure of Lambda Expressions
The basic syntax of a lambda is:
(parameters) -> { body }
- Without parameters:
() -> System.out.println("Hello") - Single parameter:
x -> x * 2(parentheses can be omitted) - Multiple parameters:
(x, y) -> x + y - Multi-line body: if the body contains multiple statements, braces
{}and an explicitreturnstatement are required.
MathOperation detailedAddition = (a, b) -> {
System.out.println("Adding...");
return a + b;
};
Standard Functional Interfaces in Java
The java.util.function package provides several built-in functional interfaces:
Predicate<T>: accepts an argument of typeTand returns a boolean (test(T t)method).Consumer<T>: accepts an argument of typeTand performs an operation without returning a result (accept(T t)method).Function<T, R>: accepts an argumentTand returns a resultR(apply(T t)method).Supplier<T>: accepts no arguments and returns a value of typeT(get()method).
Try it yourself
Complete the code by instantiating the Calculator interface using a lambda expression that adds two integers. Then, invoke the calculate method passing 5 and 3, and print the result.
Show hint
Declare `Calculator adder = (a, b) -> a + b;` and then invoke `adder.calculate(5, 3)` inside the print call.
Solution available after 3 attempts
Create an instance of the standard functional interface Predicate<String> named isLong using a lambda expression that checks if the string length is greater than 5 characters. Then print the test result for 'hello world'.
Show hint
The lambda for a `Predicate<String>` takes a parameter `s` and returns `s.length() > 5` as a boolean condition.
Solution available after 3 attempts
Sort the list of strings names alphabetically by invoking the sort() method on it and passing a lambda expression that implements Comparator (taking two strings s1, s2 and comparing them using compareTo).
Show hint
Use `names.sort((s1, s2) -> s1.compareTo(s2));` to sort the list in place.
Solution available after 3 attempts