当前位置:网站首页>Lambda expressions and method references
Lambda expressions and method references
2022-07-02 05:56:00 【Want to eat pineapple crisp】
Lambda expression
brief introduction
- Lambda The expression is an anonymous function , A function that has no function name .
- stay Java 8 Before , Writing code for an anonymous inner class is tedious 、 Poor readability .
- Lambda The application of expressions makes the code more compact , Readability enhancements ; in addition ,Lambda Expressions make it convenient to operate large sets in parallel , Can give full play to multi-core CPU The advantages of , Easier to code for multicore processors .
grammar
- A comma separated list of formal parameters in parentheses : In fact, it is the parameter of the abstract method in the interface ;
- An arrow symbol :
->, This arrow is also called Lambda Operator or arrow operator ; - Method body : Can be expressions and code blocks , Is the method body of the rewritten method .
The method body is the expression , The value of the expression is returned as the return value .
// grammar
(parameters) -> expression
// Example , Returns the value of adding two numbers
(num1,num2) -> num1+num2
Method body is code block , Must use {} Come and wrap it up , And need a return Return value , But if the return value of the method in the functional interface is void, Then there is no need to return the value .
// grammar
(parameters) -> {
statement1;
statement2;
return value;
}
// Example , Print two numbers separately , No return
(num1,num2) -> {
System.out.println(num1);
System.out.println(num2);
}
// Example , Print two numbers separately , Return additive value
(num1,num2) -> {
System.out.println(num1);
System.out.println(num2);
return num1+num2;
}
example
No parameter, no return value
No parameter, no return value , It means that the method of interface implementation class rewriting has no parameters and no return value , Runnable Interface anonymous inner classes belong to this class :
public class LambdaDemo2 {
public static void main(String[] args) {
// Instantiate a through an anonymous inner class instance Runnable Implementation class of interface
Runnable runnable1 = new Runnable() {
@Override
public void run() {
// Method invisible parameter list , No return value
System.out.println("Hello, Anonymous inner class ");
}
};
// Execute anonymous inner class run() Method
runnable1.run();
// No parameter, no return value , adopt lambda Expression to instantiate Runnable Implementation class of interface
Runnable runnable2 = () -> System.out.println("Hello, Lambda");
// Carry out by lambda Expression instantiated object run() Method
runnable2.run();
}
}
Running results :
Hello, Anonymous inner class
Hello, Lambda
Single parameter has no return value
No parameter, no return value , It refers to that the method of interface implementation class rewriting is a single parameter , The return value is void Of , Examples are as follows :
import java.util.function.Consumer;
public class LambdaDemo3 {
public static void main(String[] args) {
// Single parameter has no return value
Consumer<String> consumer1 = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
consumer1.accept("Hello World!");
Consumer<String> consumer2 = (String s) -> {
System.out.println(s);
};
consumer2.accept(" Hello , The world !");
}
}
Running results :
Hello World!
Hello , The world !
Omit data types
What is omitting data types ? We still use the above example , Use Lambda Expressions can omit types in parentheses , The example code is as follows :
// Omit the pre type code
Consumer<String> consumer2 = (String s) -> {
System.out.println(s);
};
consumer2.accept(" Hello , The world !");
// Omit the code after type
Consumer<String> consumer3 = (s) -> {
System.out.println(s);
};
consumer3.accept(" Hello , The world !");
Tips: The reason why the data type in brackets can be omitted , It's because we are Comsumer<String> Generics have been specified at , The compiler can infer the type , There is no need to specify the specific type later . It is called type inference .
Omit the parentheses of the parameter
When we write Lambda When an expression requires only one parameter , The parentheses of parameters can be omitted , Rewrite the code of the above example :
// Omit the code before the parentheses
Consumer<String> consumer3 = (s) -> {
System.out.println(s);
};
consumer3.accept(" Hello , The world !");
// Omit the code after the parentheses
Consumer<String> consumer4 = s -> {
System.out.println(s);
};
consumer3.accept(" Hello , The world !");
Observe the example code , Previous (s) -> It can be rewritten as s ->, This is also legal .
Omit return And braces
When Lambda When the expression body has only one statement , If there is a return , be return And braces can be omitted , The example code is as follows :
import java.util.Comparator;
public class LambdaDemo4 {
public static void main(String[] args) {
// Omit return and {} Front code
Comparator<Integer> comparator1 = (o1, o2) -> {
return o1.compareTo(o2);
};
System.out.println(comparator1.compare(12, 12));
// Omit return and {} Post code
Comparator<Integer> comparator2 = (o1, o2) -> o1.compareTo(o2);
System.out.println(comparator2.compare(12, 23));
}
}
Running results :
0
-1
Method reference
brief introduction
Method reference (Method References) It's a kind of grammar sugar , It's essentially Lambda expression , We know Lambda Expressions are instances of functional interfaces , So method references are also instances of functional interfaces .
grammar
Method references use a pair of colons (::) To quote methods , The format is as follows :
Class or object :: Method name
// Example
System.out::println
Usage scenarios and conditions
The usage scenario referenced by the method is : When it comes to Lambda Operation of body , There is already a way to do it , You can use methods to reference .
The usage condition of method reference is : The parameter list and return value type of the abstract method in the interface are the same as the method parameter list and return value of the method reference .
Classification of method references
For the use of method references , It can be divided into the following 4 In this case :
- object :: Non static methods : Object references non static methods , That is, instance method ;
- class :: Static methods : Class references static methods ;
- class :: Non static methods : Class references non static methods ;
- class :: new: Construction method reference .
Object references instance methods
Object references instance methods , We've already mentioned above ,System.out It's the object , and println Is the instance method , No more details here .
Class references static methods
Class references static methods , Please check the following examples :
import java.util.Comparator;
import java.util.function.Function;
public class MethodReferencesDemo3 {
public static void main(String[] args) {
// Use Lambda expression
Function<Double, Long> function1 = d -> Math.round(d);
Long apply1 = function1.apply(1.0);
System.out.println(apply1);
// Use method reference , class :: Static methods ( round() Is a static method )
Function<Double, Long> function2 = Math::round;
Long apply2 = function2.apply(2.0);
System.out.println(apply2);
}
}
Running results :
1
2
Class references instance methods
Class references instance methods , It's hard to understand , Please check the following examples :
import java.util.Comparator;
public class MethodReferencesDemo4 {
public static void main(String[] args) {
// Use Lambda expression
Comparator<String> comparator1 = (s1, s2) -> s1.compareTo(s2);
int compare1 = comparator1.compare("Hello", "Java");
System.out.println(compare1);
// Use method reference , class :: Example method ( compareTo() For example method )
Comparator<String> comparator2 = String::compareTo;
int compare2 = comparator2.compare("Hello", "Hello");
System.out.println(compare2);
}
}
Running results :
-2
0
Class reference constructor
Class reference constructor , You can use the class name directly :: new, Please see the following example :
import java.util.function.Function;
import java.util.function.Supplier;
public class MethodReferencesDemo5 {
static class Person {
private String name;
public Person() {
System.out.println(" The parameterless construction method is implemented ");
}
public Person(String name) {
System.out.println(" The single parameter construction method performs ");
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
// Use Lambda expression , Call parameterless constructor
Supplier<Person> supplier1 = () -> new Person();
supplier1.get();
// Use method reference , Reference parameterless construction method
Supplier<Person> supplier2 = Person::new;
supplier2.get();
// Use Lambda expression , Call the single parameter constructor
Function<String, Person> function1 = name -> new Person(name);
Person person1 = function1.apply(" Xiaomu ");
System.out.println(person1.getName());
// Use method reference , Reference the single parameter construction method
Function<String, Person> function2 = Person::new;
Person person2 = function1.apply(" Xiao Ming ");
System.out.println(person2.getName());
}
}
Running results :
The parameterless construction method is implemented
The single parameter construction method performs
Xiaomu
The single parameter construction method performs
Xiao Ming
In the example , We used Lambda Expression and method reference are two ways , Static inner classes are called respectively Person Nonparametric and single parameter construction method of . The formal parameter list of the abstract method in the functional interface is consistent with that of the constructor , The return value type of an abstract method is the type to which the constructor belongs .
边栏推荐
- Some experience of exercise and fitness
- Zzuli:1065 count the number of numeric characters
- 51单片机——ADC讲解(A/D转换、D/A转换)
- Oled12864 LCD screen
- Reading notes of cgnf: conditional graph neural fields
- Zzuli:1060 numbers in reverse order
- Generics and generic constraints of typescript
- RGB 无限立方体(高级版)
- Several keywords in C language
- Regular expression summary
猜你喜欢

Software testing Q & A
![[PHP是否安装了 SOAP 扩]对于php实现soap代理的一个常见问题:Class ‘SoapClient‘ not found in PHP的处理方法](/img/25/73f11ab2711ed2cc9f20bc7f9116b6.png)
[PHP是否安装了 SOAP 扩]对于php实现soap代理的一个常见问题:Class ‘SoapClient‘ not found in PHP的处理方法

Cube magique infini "simple"

Huawei Hongmeng OS, is it OK?

51单片机——ADC讲解(A/D转换、D/A转换)

脑与认知神经科学Matlab Psytoolbox认知科学实验设计——实验设计四

如何写出好代码 — 防御式编程指南

Balsamiq wireframes free installation

"Simple" infinite magic cube

Can't the dist packaged by vite be opened directly in the browser
随机推荐
mysql事务和隔离级别
mock-用mockjs模拟后台返回数据
PHP 开发与测试 Webservice(SOAP)-Win
PHP array to XML
[Chongqing Guangdong education] selected reading reference materials of British and American literature of Nanyang Normal University
1036 Boys vs Girls
Eco express micro engine system has supported one click deployment to cloud hosting
Stick to the big screen UI, finereport development diary
DRM display framework as I understand it
OLED12864 液晶屏
Happy Lantern Festival | Qiming cloud invites you to guess lantern riddles
【LeetCode】Day92-盛最多水的容器
1036 Boys vs Girls
外部中断无法进入,删代码再还原就好......记录这个想不到的bug
php获取cpu使用率、硬盘使用、内存使用
数理统计与机器学习
Common websites for Postgraduates in data mining
Web页面用户分步操作引导插件driver.js
PHP obtains some values in the string according to the specified characters, and reorganizes the remaining strings into a new array
all3dp.com网站中全部Arduino项目(2022.7.1)