This is the 8th day of my participation in Gwen Challenge
Introduction to Lambda Expressions
The main purpose of Lambda expressions is to replace the cumbersome syntax of anonymous inner classes. It consists of three parts: parameter list, arrow, and code block.
Let's take a look at an example and then we'll talk a little bit about Lambda. public class Test { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println(" I am an anonymous class "); }}); // We can use Lambda expressions to replace new Thread(() -> system.out.println (" I am Lambda")); // Is it much simpler? }}Copy the code
Given the power of Lambda expressions, let’s look at the basic syntax of Lambda.
Syntax for lambda expressions
Lambda expressions are essentially functions. Int sub(int a,int b){return a-b; } Lambda expressions are defined without types and function names. (Parameter...) ->{method body}Copy the code
Details on the syntax of lambda expressions
1. The parameter list of a Lambda expression can be omitted. If the parameter list has only one argument, the parentheses can also be omitted. 2. The arrow must contain a hyphen () and a greater than (). 3. If there is only one return statement, omit the return keywordCopy the code
Lambda representation and functional interface
The type of Lanbda expression must be a functional interface, which represents the interface of an abstract method. A functional interface can contain multiple default methods, class methods, but only one abstract method.
Lambda expressions implement anonymous methods, so they implement only one method in a particular functional interface. So Lambda expressions have two limitations: 1. The target type of a Lambda expression must be an explicit functional interface; 2. Lambda expressions can only create objects for functional interfaces. Lambda expressions can only create objects for interfaces that have only one abstract method. There are usually three ways to ensure that a lambda expression is limited: 1. Assign a lambda expression to a variable of a functional interface type. 2. Pass a Lambda expression as a functional interface type to a method. 3. Cast Lambda expressions using functional interfaces.Copy the code
It is important to note that the type and number of arguments in a lambda expression must have the same parameter list as the abstract methods in a functional interface.
The above is my shallow view of Lambda expressions, if there are shortcomings or errors welcome to leave a comment.
Lambda expressions don’t stop there. Next time, we’ll take a closer look at other uses of Lambda.