Java8 Lambda Expressions
# Java Lambda Expressions
[ Java 8 New Features](#)
* * *
Lambda expressions, also known as closures, are the most important new feature driving the release of Java 8.
Lambda allows passing a function as a parameter to a method (passing a function as an argument into a method).
Using Lambda expressions can make code more concise and compact.
### Syntax
The syntax format for lambda expressions is as follows:
(parameters) ->expression or (parameters) ->{statements; }
`parameters` is the parameter list, and `expression` or `{ statements; }` is the body of the Lambda expression. If there is only one parameter, the parentheses can be omitted; if there are no parameters, empty parentheses are still required.
Here is a simple example demonstrating the use of a Lambda expression to calculate the sum of two numbers:
## Example
// Using Lambda expression to calculate the sum of two numbers
MathOperation addition =(a, b)-> a + b;
// Calling the Lambda expression
int result = addition.operation(5, 3);
System.out.println("5 + 3 = "+ result);
In the example above, `MathOperation` is a functional interface containing an abstract method `operation`. The Lambda expression `(a, b) -> a + b` implements this abstract method, representing an addition operation on two parameters.
Lambda expressions can be used in various scenarios, including collection operations, event handling, etc. Here is an example of using a Lambda expression to iterate over a list:
## Example
List names =Arrays.asList("Alice", "Bob", "Charlie");
// Using Lambda expression to iterate over the list
names.forEach(name ->System.out.println(name));
Lambda expressions introduce a more functional programming style to Java, making code more concise and readable. They represent a significant improvement for functional programming in Java 8.
* * *
## Key Features
### Conciseness
Lambda expressions provide a more concise syntax, especially suitable for functional interfaces. Compared to traditional anonymous inner classes, Lambda expressions make code more compact and reduce boilerplate code.
## Example
// Traditional anonymous inner class
Runnable runnable1 =new Runnable(){
@Override
public void run(){
System.out.println("Hello World!");
}
};
// Using Lambda expression
Runnable runnable2 =()->System.out.println("Hello World!");
### Functional Programming Support
Lambda expressions are an embodiment of functional programming, allowing functions to be passed as parameters to methods or returned as values. This support makes Java more flexible in functional programming, enabling better handling of collection operations, parallel computing, and other tasks.
## Example
// Using Lambda expression as a parameter passed to a method
List names =Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name ->System.out.println(name));
### Variable Capture
Lambda expressions can access variables from the outer scope, a feature known as variable capture. Lambda expressions can implicitly capture final or effectively final local variables.
## Example
// Variable capture
int x =10;
MyFunction myFunction = y ->System.out.println(x + y);
myFunction.doSomething(5);// Outputs 15
### Method References
Lambda expressions can be further simplified through method references. Method references allow you to directly reference methods of existing classes or objects without writing redundant code.
## Example
// Using method references
List names =Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(System.out::println);
### Parallelizability
Lambda expressions make it easier to implement parallel operations. By using the Stream API in conjunction with Lambda expressions, parallel computing can be implemented more easily, improving program performance.
## Example
// Using Lambda expressions and Stream API for parallel computation
List numbers =Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.parallelStream().mapToInt(Integer::intValue).sum();
The introduction of Lambda expressions makes Java programming more flexible, concise, and promotes the development of functional programming.
* * *
## Lambda Expression Examples
Simple examples of Lambda expressions:
// 1. No parameters, returns 5 () -> 5 // 2. Takes one parameter (numeric type), returns its double value x -> 2 * x // 3. Takes two parameters (numeric), returns their difference (x, y) -> x β y // 4. Takes two int integers, returns their sum (int x, int y) -> x + y // 5. Takes a string object, prints to console, returns no value (appears to return void) (String s) -> System.out.print(s)
Enter the following code in the Java8Tester.java file:
## Java8Tester.java File
public class Java8Tester{public static void main(String args[]){Java8Tester tester = new Java8Tester(); // Type declaration MathOperation addition = (int a, int b) ->a + b; // Without type declaration MathOperation subtraction = (a, b) ->a - b; // Return statement in curly braces MathOperation multiplication = (int a, int b) ->{return a * b; }; // Without curly braces and return statement MathOperation division = (int a, int b) ->a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, addition)); System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction)); System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication)); System.out.println("10 / 5 = " + tester.operate(10, 5, division)); // Without parentheses GreetingService greetService1 = message ->System.out.println("Hello " + message); // With parentheses GreetingService greetService2 = (message) ->System.out.println("Hello " + message); greetService1.sayMessage(""); greetService2.sayMessage("Google"); }interface MathOperation{int operation(int a, int b); }interface GreetingService{void sayMessage(String message); }private int operate(int a, int b, MathOperation mathOperation){return mathOperation.operation(a, b); }}
Execute the above script, the output result is:
$ javac Java8Tester.java $ java Java8Tester10 + 5 = 1510 - 5 = 510 x 5 = 5010 / 5 = 2Hello TutorialHello Google
Using Lambda expressions requires attention to the following two points:
* Lambda expressions are primarily used to define method type interfaces for inline execution (e.g., a simple method interface). In the example above, we used various types of Lambda expressions to define the method of the `MathOperation` interface, and then we defined the execution of `operation`.
* Lambda expressions eliminate the trouble of using anonymous methods and give Java simple but powerful functional programming capabilities.
* * *
## Variable Scope
Lambda expressions can only reference outer local variables marked as `final`. This means you cannot modify local variables defined outside the scope within the lambda, otherwise a compilation error will occur.
Enter the following code in the Java8Tester.java file:
## Java8Tester.java File
public class Java8Tester{final static String salutation = "Hello! "; public static void main(String args[]){GreetingService greetService1 = message ->System.out.println(salutation + message); greetService1.sayMessage(""); }interface GreetingService{void sayMessage(String message); }}
Execute the above script, the output result is:
$ javac Java8Tester.java $ java Java8TesterHello!
We can also directly access outer local variables within the lambda expression:
## Java8Tester.java File
public class Java8Tester{public static void main(String args[]){final int num = 1; Converters = (param) ->System.out.println(String.valueOf(param + num)); s.convert(2); // Output is 3}public interface Converter{void convert(int i); }}
YouTip