This article brings you relevant knowledge about java, which mainly introduces issues related to Lambda expressions. Lambda expressions introduce an operator in the Java language**" ->”**, this operator is called Lambda operator or arrow operator. Let’s take a look at it. I hope it will be helpful to everyone.
Recommended learning: "java Video Tutorial"
We know that in Java, interfaces cannot be instantiated, but interfaces An object can point to its implementation class object. What if the interface doesn't even have an implementation object? You can also use anonymous classes, as follows:
public class JavaTest { public static void main(String[] args) { Fly fly = new Fly() { @Override public void fly(String name) { System.out.println(name + "飞行"); } }; fly.fly("张三"); }}interface Fly{ abstract void fly(String name);}
However, using the anonymous internal method, the amount of code is actually not very concise. In order to make the code more concise, Java introduced Lambda Expression writing uses simpler syntax to achieve this function. The simplified code using Lambda expressions is as follows:
public class JavaTest { public static void main(String[] args) { Fly fly = name -> System.out.println(name + "飞行"); fly.fly("张三"); }}interface Fly{ abstract void fly(String name);}
The same effect is achieved through Lambda expressions, but the amount of code is streamlined. That's right, this is the charm of Lambda expressions.
Before learning the syntax of Lambda expressions, you must first know what functional interface has only one method to be implemented The interface is called a functional interface.
//接口中只有一个待实现的方法 fly,所以这是函数式接口interface Fly{ void fly(String name);}//接口中有两个待实现的方法 这是不是函数式接口interface Run{ void fastRun(); void slowRun();}//接口中有两个方法,但其中一个是已经定义好的default方法,真正需要子类去实现的方法只有一个 这是函数式接口interface Jump{ void jump(); default void highJump(){ System.out.println("跳的更高"); }}
You can add the **@FunctionalInterface annotation on the interface to assert that the interface is a functional interface. If the interface is not a functional interface, the compilation will prompt an error.
Why do you need to know what a functional interface is? Because Lambda expressions simplify the anonymous class implementation of an interface, it only works on functional interfaces**.
This is easy to understand. If an interface has multiple methods to be implemented, the Lambda expression cannot tell which method in the interface it is implementing.
Lambda expression introduces an operator **"->"** in the Java language, which is Called Lambda operator or arrow operator. It divides Lambda into two parts:
The left side: specifies all the parameters required by the Lambda expression
The right side: formulates the Lambda body, that is, the function to be performed by the Lambda expression.
Like this:
(parameters) -> expression 或 (parameters) ->{ statements; }
Except for -> and Lambda body, other parameters of Lambda expressions, such as parameters, parentheses, and square brackets, can be omitted based on the parameter type and method body code line number. .
Take the implementation of the following functional interface as an example:
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); } interface NoParam{ int returnOne(); }
The following are the important characteristics of lambda expressions:
// 类型声明 MathOperation addition = (int a, int b) -> a + b; // 不用类型声明 MathOperation subtraction = (a, b) -> a - b;
// 不用括号 GreetingService greetService1 = message -> System.out.println("Hello " + message); // 用括号 GreetingService greetService2 = (message) -> System.out.println("Hello " + message);
// 多条语句不可以省略大括号 MathOperation multiplication = (int a, int b) -> { int num = a+1; num = a + b; return a * b + num; }; // 单条语句可以省略大括号 MathOperation pision = (int a, int b) -> a / b;
// 多条语句的Lambda表达式如果有返回值,需要使用return MathOperation multiplication = (int a, int b) -> { int num = a+1; num = a + b; return a * b + num; }; // 单条语句可以省略return MathOperation pision = (int a, int b) -> a / b;
Lambda expressions are not just used to simplify the creation of an anonymous class, it has more uses.
In the above, the usage of Lambda expressions is to assign values to variables. This can simplify the code segment of anonymous inner class assignment and improve reading efficiency.
MathOperation subtraction = (a, b) -> a - b;
interface MathOperation { int operation(int a, int b); } MathOperation getOperation(int a, int b){ return (a1, b1) -> a+b; }
MathOperation math[] = { (a,b) -> a+b, (a,b) -> a-b, (a,b) -> a*b };
public static void main(String args[]){ Java8Tester java8Tester = new Java8Tester(); java8Tester.operate(1,2,((a, b) -> a*b)); } private int operate(int a, int b, MathOperation mathOperation){ return mathOperation.operation(a, b); } interface MathOperation { int operation(int a, int b); }
Within the Lambda expression expression body, you can access variables outside the expression body, but you cannot modify other variables.
When learning Lambda, you may also find a strange way of writing, such as the following code:
// 方法引用写法GreetingService greetingService = System.out::println; greetingService.sayMessage("hello world");
A symbol that I have never seen before appears here::. This way of writing is called a method reference.
Obviously, using method references is simpler than ordinary Lambda expressions.
If the implementation of the functional interface happens to be implemented by calling a method, then we can use method references.
public class Java8Tester { public static void main(String args[]){ // 静态方法引用--通过类名调用 GreetingService greetingService = Test::MyNameStatic; greetingService.sayMessage("hello"); Test t = new Test(); //实例方法引用--通过实例调用 GreetingService greetingService2 = t::myName; // 构造方法方法引用--无参数 Supplier<test> supplier = Test::new; System.out.println(supplier.get()); } interface GreetingService { void sayMessage(String message); }}class Test { // 静态方法 public static void MyNameStatic(String name) { System.out.println(name); } // 实例方法 public void myName(String name) { System.out.println(name); } // 无参构造方法 public Test() { }}</test>
更少的代码行-lambda表达式的最大好处之一就是减少了代码量。我们知道,lambda表达式只能与功能接口一起使用。例如,Runnable 是一个接口,因此我们可以轻松地应用lambda表达式。
通过将行为作为方法中的参数传递来支持顺序和并行执行-通过在Java 8中使用Stream API,将函数传递给collection方法。现在,集合的职责是以顺序或并行的方式处理元素。
更高的效率-过使用Stream API和lambda表达式,可以在批量操作集合的情况下获得更高的效率(并行执行)。 此外,lambda表达式有助于实现集合的内部迭代,而不是外部迭代。
推荐学习:《java视频教程》
The above is the detailed content of Detailed explanation of Lambda expressions in Java examples. For more information, please follow other related articles on the PHP Chinese website!