The use of lambda expressions in functional interfaces

1. What is a functional interface

The so-called functional interface (Functional Interface) is that the current interface can only contain one abstract method to be implemented; when it comes to functional interface, it is necessary to talk about an annotation @FunctionalInterface , which is an empty annotation, mainly used for compilation Level error checking , plus this annotation, the compiler will report an error when the interface you write does not conform to the functional interface definition. Here are a few examples:
Insert picture description here
Insert picture description here
Insert picture description here
From the above, it can be seen that if there are more than one or no abstract methods to be implemented in the interface, it does not conform to the definition of a functional interface. When the @FunctionalInterface annotation is added, there will be an out-of-format prompt. If you need to provide other methods in the functional interface, you can use the default method to provide them after jdk1.8.

2. Use Lambda expressions to implement functional interfaces

The functional interfaces are as follows:

@FunctionalInterface
public interface LambdaEx1 {
    
    
	Integer calculate(Integer a,Integer b);
}

The use of the interface is as follows:

	// 在jdk1.8之前使用匿名内部类
	public static void main(String[] args) {
    
    
		LambdaEx1 lambdaEx=new LambdaEx1() {
    
    
			@Override
			public Integer calculate(Integer a, Integer b) {
    
    
				return Math.addExact(a, b);
			}
		};
		System.out.println(lambdaEx.calculate(10, 20));
	}
	// 在jdk1.8之后使用lambda表达式
	public static void main(String[] args) {
    
    
		LambdaEx1 lambdaEx1=(val1,val2)->{
    
    
			return Math.addExact(val1, val2);		
		};
		System.out.println(lambdaEx1.calculate(10,20));
	}

Note:
    Only functional interfaces can use lambda expressions, other interfaces or methods cannot be used. In the daily development process, there are many examples of functional interfaces using lambda expressions, such as the implementation of the **forEach()** method in the map interface; the implementation of the run method in multithreading.

Guess you like

Origin blog.csdn.net/qgnczmnmn/article/details/108669710