3.1 Lambda Expressions Explained
Lambda expressions in Java are a concise way to represent instances of functional interfaces. They allow you to pass behavior as an argument to methods, making your code more readable and expressive. Understanding lambda expressions is crucial for mastering modern Java programming.
Key Concepts
1. Functional Interfaces
A functional interface is an interface that contains exactly one abstract method. Lambda expressions can be used to implement these interfaces without the need for a separate class. Common examples include Runnable
, Comparator
, and Predicate
.
Example
@FunctionalInterface interface MyFunctionalInterface { void myMethod(); } MyFunctionalInterface lambda = () -> System.out.println("Hello, Lambda!"); lambda.myMethod(); // Output: Hello, Lambda!
2. Syntax of Lambda Expressions
A lambda expression consists of a parameter list, an arrow token (->
), and a body. The body can be a single expression or a block of statements. The syntax varies depending on the number of parameters and the complexity of the body.
Example
// No parameters Runnable runnable = () -> System.out.println("No parameters"); // One parameter Predicate<String> predicate = (s) -> s.isEmpty(); // Multiple parameters Comparator<Integer> comparator = (a, b) -> a.compareTo(b);
3. Method References
Method references are a shorthand way to write lambda expressions that call a specific method. They can refer to static methods, instance methods, or constructors. Method references make the code more concise and readable.
Example
// Static method reference Function<String, Integer> function = Integer::parseInt; // Instance method reference Predicate<String> predicate = String::isEmpty; // Constructor reference Supplier<List<String>> supplier = ArrayList::new;
Examples and Analogies
Think of a lambda expression as a shortcut for writing a method that can be passed around like a variable. For example, imagine you have a list of tasks, and you want to sort them by priority. Instead of writing a separate method for the sorting logic, you can use a lambda expression to define the sorting behavior inline.
By mastering lambda expressions, you can write more expressive and concise code, making your Java SE 11 applications more modern and efficient.