English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)/O)

Java Reader/Java Writer

Other Java topics

Java Lambda Expressions

Java 8 New Features

Lambda expressions, also known as closures, are what drive Java 8 The most important new feature released.

Lambda allows a function to be passed as a method parameter (a function is passed into the method as a parameter).

Using Lambda expressions can make the code more concise and compact.

Syntax

The syntax format of lambda expressions is as follows:

(parameters) -> expression
or
(parameters) -{ statements; }

Here are the important features of lambda expressions:

  • Optional type declaration:No need to declare parameter types, the compiler can identify parameter values uniformly.

  • Optional parameter parentheses:A single parameter does not need to be defined with parentheses, but multiple parameters require parentheses.

  • Optional curly braces:If the body contains a statement, no curly braces are needed.

  • Optional return keyword:If the body of the expression contains only one expression, the compiler will automatically return the value, and curly braces are required to specify that the expression returns a numerical value.

Lambda expression example

Simple example of Lambda expression:

// 1. without parameters, the returned value is 5  
() -> 5  
  
// 2. accept a parameter (number type), returning its2the value of a multiple  
x -> 2 * x  
  
// 3. accept2parameters (numbers), and return their difference  
(x, y) -> x - y  
  
// 4. accept2an int integer, returning their sum  
(int x, int y) -> x + y  
  
// 5. accept a string object, and print it to the console without returning any value (it looks like it returns void)  
(String s) -> System.out.print(s)

In Java8Enter the following code into the Tester.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;
        
      // No type declaration
      MathOperation subtraction = (a, b) -> a - b;
        
      // Return statements within curly braces
      MathOperation multiplication = (int a, int b) -> { return a * b; };
        
      // No curly braces or return statements
      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);
        
      // Using parentheses
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
        
      greetService1.sayMessage("w3codebox");
      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, and the output result is:

$ javac Java8Tester.java 
$ java Java8Tester
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello w3codebox
Hello Google

There are two points to note when using Lambda expressions:

  • Lambda expressions are mainly used to define inline method types interfaces, such as a simple method interface. In the above example, we use various types of Lambda expressions to define the methods of the MathOperation interface. Then we define the execution of sayMessage.

  • Lambda expressions eliminate the trouble of using anonymous methods and provide Java with simple but powerful functional programming capabilities.

Variable scope

Lambda expressions can only reference outer local variables marked as final, which means that local variables defined outside the scope cannot be modified within the lambda expression, otherwise a compilation error will occur.

In Java8Enter the following code into the Tester.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("w3codebox");
   }
    
   interface GreetingService {
      void sayMessage(String message);
   }
}

Execute the above script, and the output result is:

$ javac Java8Tester.java 
$ java Java8Tester
Hello! w3codebox

We can also directly access the outer local variables in the lambda expression:

public class Java8Tester {
    public static void main(String args[]) {
        final int num = 1;
        Converter<Integer, String> s = (param -> System.out.println(String.valueOf(param + num));
        s.convert(2);  // The output result is 3
    }
 
    public interface Converter<T1, T2> {
        void convert(int i);
    }
}

Local variables in lambda expressions do not need to be declared as final, but they must not be modified by subsequent code (i.e., they have the semantics of being final implicitly).

int num = 1;  
Converter<Integer, String> s = (param -> System.out.println(String.valueOf(param + num));
s.convert(2);
num = 5;  
//Error message: Local variable num defined in an enclosing scope must be final or effectively 
 final

It is not allowed to declare a parameter or local variable with the same name as a local variable in a Lambda expression.

String first = "";  
Comparator<String> comparator = (first, second); -> Integer.compare(first.length(), second.length());  //Compilation Error

Java 8 New Features