Lambda Expression and functional interface

1, An overview of functional programming

           In Mathematics , A function has an input , A set of calculation scheme of output , that is “ What do you do with something ”. Relatively speaking , Object oriented Sub emphasis “ You have to do things in the form of objects
”, But the function thought ignores the object-oriented complex syntax as far as possible —— Emphasize what to do , Instead of using In what form . Object oriented thinking : Do one thing , Find someone who can solve this problem , Call the method of the object ,
Get things done . The idea of functional programming : As long as we can get the results , Who did it , It doesn't matter what you do , It's the result that counts , Not paying attention to process .

2, Redundant Rinnable code

When a thread needs to be started to complete a task , Usually through java.lang.Runnable Interface to define the task content , And use java.lang.Thread
Class to start the thread . The code is as follows :
public class Demo01Runnable { public static void main(String[] args) { //
Anonymous Inner Class Runnable task = new Runnable() { @Override public void run() { //
Override abstract methods System.out.println(" Multithreaded task execution !"); } }; new Thread(task).start(); // Start thread
} }
code analysis

about Runnable Anonymous inner class usage of , Several points can be analyzed

* Thread Class needs Runnable Interface as a parameter , Abstract methods run Method is the core used to specify the content of a threaded task .
* To specify run The body of the method , It has to be realized Runnable Interface implementation class .
* To avoid defining a RunnableImpl The trouble of implementing classes , You have to use anonymous inner classes .
* The override abstraction must be overridden run method .
* actually , It can be found that only run Method body is the key .
3, experience Lambda A better way to write
public class Demo02LambdaRunnable { public static void main(String[] args) {
new Thread(() ‐ > System.out.println(" Multithreaded task execution !")).start(); // Start thread } }
first , Use the implementation class first , Anonymous inner class . And then with Lambda Expression comparison . To start a thread , Need to create Thread Class and call start method .
To specify what the thread executes , Call required Thread Construction method of class .

* public Thread(Runnable target)
Using implementation classes

In order to obtain Runable Implementation object of interface , You can define an implementation class for the interface RunnableImpl:
public class RunnableImpl implements Runnable { @Override public void run() {
System.out.println(" Multithreaded task execution !"); } }
Then create the object of the implementation class as the Thread Construction method of class
public class Demo03ThreadInitParam { public static void main(String[] args) {
Runnable task = new RunnableImpl(); new Thread(task).start(); } }
Using anonymous inner classes
this RunnableImpl Class is just for implementation Runnable Interface , And it was used only once , So use anonymous inner classes
Syntax can omit a separate definition of the class , Anonymous inner class : public class Demo04ThreadNameless { public static void
main(String[] args) { new Thread(new Runnable() { @Override public void run() {
System.out.println(" Multithreaded task execution !"); } }).start(); } } Advantages and disadvantages of anonymous inner class : one side , Anonymous inner classes can help us
Omit the definition of the implementation class ; on the other hand , Syntax of anonymous inner classes —— It's really complicated ! Analyze the semantics in the code carefully , Runnable There is only one interface run Definition of method :
* public abstract void run(); That is to make a plan to do things ( It's actually a function ):
* No parameter : The scheme can be implemented without any conditions .
* No return value : The program produced no results .
* Code block ( Method body ): The specific implementation steps of the program . The same semantics is embodied in Lambda In grammar , It's simpler :
* () ‐> System.out.println(" Multithreaded task execution !")
* The first pair of parentheses is run Parameters of the method ( nothing ), Representatives don't need any conditions ;
* An arrow in the middle represents passing the previous parameter to the following code ;
* The following output statement is the business logic code .
4,Lambda standard format

 Lambda Leave out the object-oriented rules , Format by 3 It consists of three parts :

* Some parameters
* An arrow
* A piece of code Lambda Expression standard format by :   ( Parameter type Parameter name ) ‐> { Code statement } Format description :
* The syntax in parentheses is consistent with the traditional method parameter list : Leave blank if there is no parameter ; Multiple parameters are separated by commas .
* -> It is a new syntax format , Represents pointing action .
* The syntax in braces is basically consistent with the requirements of traditional method body .
5, practice
demand :
* Using arrays to store multiple Person object
* For the Person Object usage Arrays Of sort Methods ascending order by age
be careful : use Lambda Expression time , Interface must be functional ( There can only be one abstract method within an interface )
package com.sunny.lambda02; public class Person { private String name; private
int age; public Person() { } public Person(String name, int age) { =
name; this.age = age; } @Override public String toString() { return "Person{" +
"name='" + name + '\'' + ", age=" + age + '}'; } public String getName() {
return name; } public void setName(String name) { = name; } public
int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package com.sunny.lambda02; import java.util.Arrays; import
java.util.Comparator; public class ArraysDemo { public static void
main(String[] args) { Person[] arr = { new Person(" Yang Mi ", 20), new Person(" Pan Panpan ",
24), new Person(" Delireba ", 13) }; // How to use anonymous inner classes Arrays.sort(arr, new
Comparator<Person>() { @Override public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge(); } }); for (Person person : arr) {
System.out.println(person.toString()); }
System.out.println("______________________"); // use Lambda To achieve . Arrays.sort(arr,
(Person o1, Person o2) -> { return o1.getAge() - o2.getAge(); }); // Simplified way .
When there is only one in the abstract method body return Statement time . It can be omitted return // If the method has only one statement , You can omit the braces that contain the body
Arrays.sort(arr, (Person o1, Person o2) -> o1.getAge() - o2.getAge()); for
(Person person : arr) { System.out.println(person.toString()); } } }
6,Lambda Ellipsis format

  Ellipsis rule

stay Lambda Based on the standard format , The rule of ellipsis is :

1. The types of parameters in parentheses can be omitted ;

2. If there is only one parameter in the parenthesis , The parentheses can be omitted ;

3. If there is only one statement in the braces , Whether or not there is a return value , You can omit braces ,return Keywords and semicolons .  

7,Lambda The premise of using
Lambda The grammar is very concise , No object-oriented complexity at all . However, there are several problems that need special attention when using :
*   use Lambda Must have interface , It requires that there is only one abstract method in the interface . No matter what JDK Built in Runnable , Comparator
Interface or custom interface , Only if the abstract method in the interface exists and is unique , Can be used Lambda.
*   use Lambda Must have context inference . That is, the parameter or local variable type of the method must be Lambda Corresponding interface type , To use Lambda As an example of the interface .
remarks : Interface with only one abstract method , be called “ Functional interface ”.


©2019-2020 Toolsou All rights reserved,
Unity Scene loading asynchronously ( Implementation of loading interface )ESP8266/ESP32 System : Optimize system startup time vue Of v-if And v-show The difference between JS How to operate college examination for the self-taught An overview of Marxism Faster RCNN Explanation of series algorithm principle ( note )CSS architecture design NOI2019 travels IAR Installation and use tutorial sort ( one ) bubble sort