Knowledge of Lambda expressions (concepts, simplification and usage)

concept

lambda expression is one of the new features of Java 8. In essence, it is an anonymous function, which can simplify the implementation of the interface and simplify the code.

Usage qualification: only functional interfaces can use lambda expressions to simplify implementation.

  • Functional interface: the interface with only one method to be implemented is the functional interface (excluding the default method modified by default, the static method modified by static, and the toString method inherited from object)
  • The @ functional interface annotation can be used to verify whether it is a functional interface
    When writing a lambda expression, only focus on the parameter list and method body:
(Parameters)->{Method body}

Of which:

  • Parameter part: the parameter list of the method, which shall be consistent with the method parameter part in the implemented interface, including the number and type of parameters.
  • Method body part: the implementation part of the method. If the method defined in the interface has a return value, pay attention to the return of the return value during implementation.
  • ->: separate the parameter part from the method body part.
    Thin policy:

Reduced expression

The parameter type of the expression can be omitted

  • If the interface method has only one parameter, you can omit the parentheses of the lambda expression.
    For example:
//Function interface
public interface MyTest{
	void test(int a);
}
//lambda expressions 
MyTest myTest = a->{System.out.println(a);};
//Call method
myTest.test();
  • If the interface method body has only one statement, you can omit braces.
//Function interface
public interface MyTest{
	void test(int a);
}
//lambda expressions 
MyTest myTest = a->System.out.println(a);
//Call method
myTest.test(a);

  • If the interface method body has a return value, the lambda expression must have a return value.
//Function interface
public interface MyTest{
    //Method with return value
	int test(int a);
}
***********************************************************

//lambda expressions 
MyTest myTest = a->{
System.out.println(a);
return a;
};
***********************************************************

//Call method
myTest.test(a);

  • If there is only one statement in the body of the interface method and there is a return value, omit the braces and also omit the return. Otherwise, an error occurs.
//Function interface
public interface MyTest{
	int test(int a);
}
***********************************************************

//lambda expressions 
MyTest myTest = a->a*a; //Equivalent to a - > {return a * a;};
***********************************************************

//Call method
myTest.test(a);

Function reference:

In order to continue to simplify the code of too complex logic, you can call the methods already implemented elsewhere to implement the function interface. This method is called function reference. The following conditions exist:

  1. Static method reference: Class:: static method. Do not add parentheses after the method name, and the parameters and return values of the method must be the same as those of the interface
//A class in which static methods exist
public class Demo{
    //Static method
	public static void out(){
		System.out.println("This is a static method");
	}
}
***********************************************************
//Functional interface
public interface MyTest{
	void testMethod();
}
***********************************************************
//Using lambda expressions
MyTest myTest = Demo::out; //Equivalent to () - > {demo. Out();}
***********************************************************
//Call method
myTest.testMethod();
  1. Non static method reference: object:: non static method name. If the object is not instantiated, you need to new an object, that is, new object:: method name
//A class in which static methods exist
public class Demo{
    //Non static method
	public void out(){
		System.out.println("This is a static method");
	}
}
***********************************************************

//Functional interface
public interface MyTest{
	void testMethod();
}
***********************************************************

//Using lambda expressions
MyTest myTest = new Demo()::out; //Equivalent to () - > {demo. Out();}
***********************************************************

//Call method
myTest.testMethod();
  1. Reference of construction method: Class Name:: new. This method is used to construct methods without parameters or with parameters. When used, the construction method will be automatically matched, and the referenced construction methods can be distinguished by the parameters of the methods in the interface. (the method defined by an interface can be used only to obtain the object of a class)
   //Person class with three construction methods
	private static class Person {
		String name;
		int age;
		public Person() {
				System.out.println("Person The parameterless constructor of the class executes");
			}
		public Person(String name) {
				this.name = name;
				System.out.println("Person The parameterized constructor of the class is executed");
			}
		public Person(String name´╝îint age) {
				this.name = name;
				this.age = age;
				System.out.println("Person The construction method of two parameters of class is executing);
			}
**********************************************************
    //Parameterless constructor interface
  public interface MyTest1{
  			Person getNullParameter();
  }
    //A parameter constructor interface
  public interface MyTest2{
  			Person getSingleParameter(String name);
  }
   //Two parameter constructor interface
  public interface MyTest3{
  			Person getDoubleParameter(String name,int age);
  }
***********************************************************
   //Using lambda expressions
   //No parameter
   MyTest1 myTest1 = Person::new;
   //One parameter
   MyTest1 myTest1 = Person::new;
   //Two parameters
   MyTest1 myTest1 = Person::new;
   //Method of calling interface
   //No parameter
   myTest1.getNullParameter();
   //One parameter
   myTest2.getSingleParameter("myName");
   //Two parameters
   myTest3.getDoubleParameter("myName",19);
  1. Special references to object methods: if you use lambda expressions to implement some interfaces. A lambda expression contains an object. At this time, in the method body, you can directly use this object to call one of its methods to complete the overall logic. Other parameters can be used as parameters of the method calling the object. At this point, this implementation can be simplified. Expression: Object Name:: method name, and then use the interface. Method (parameter).
    For example:
	//Class of an object
 	public  class Person {		
		private String name ;
		public void setName(String name) {
			this.name = name;
		}
		public String getName() {
			return name;
		}
	}

 	//Functional interface
 	public interface MyTest{
 		String get(Person person);
 	}
 
   //Using lambda expressions
   Person person = new Person(); //Create a person object
   person.setName("zhangsan");
   MyTest myTest = Person::getName; //Equivalent to mytest mytest = (P) - > {p.getname;};

Note: if a local variable is used in a lambda expression, it will automatically become a constant and cannot be modified later. If it is a global variable, there is no problem

Tags: Java Lambda

Posted on Wed, 22 Sep 2021 09:24:34 -0400 by lcy