当前位置:网站首页>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 .
边栏推荐
- Conglin environmental protection rushes to the scientific and Technological Innovation Board: it plans to raise 2billion yuan, with an annual profit of more than 200million yuan
- Redis Key-Value数据库 【高级】
- 如何写出好代码 — 防御式编程指南
- Several keywords in C language
- 软件测试 - 概念篇
- How to write good code - Defensive Programming Guide
- keepalived安装使用与快速入门
- cookie插件和localForage离线储存插件
- PHP array to XML
- PHP extensions
猜你喜欢

Gcnet: non - local Networks meet Squeeze excitation Networks and Beyond

Cube magique infini "simple"

Mathematical statistics and machine learning

Go language web development is very simple: use templates to separate views from logic

文件包含漏洞(一)

软件测试 - 概念篇

keepalived安装使用与快速入门
![[C language] simple implementation of mine sweeping game](/img/f7/15d561b3c329847971cabd4708c851.png)
[C language] simple implementation of mine sweeping game

神机百炼3.54-染色法判定二分图

mysql事务和隔离级别
随机推荐
php按照指定字符,获取字符串中的部分值,并重组剩余字符串为新的数组
all3dp.com网站中全部Arduino项目(2022.7.1)
Practice C language advanced address book design
Test case
cookie插件和localForage离线储存插件
Pytorch Chinese document
492.构造矩形
Summary of MySQL constraints
STC8H8K系列匯編和C51實戰——數碼管顯示ADC、按鍵串口回複按鍵號與ADC數值
【C语言】简单实现扫雷游戏
[Chongqing Guangdong education] selected reading reference materials of British and American literature of Nanyang Normal University
Redis key value database [advanced]
php读文件(读取json文件,转换为数组)
php继承(extends)
Lingyunguang rushes to the scientific innovation board: the annual accounts receivable reaches 800million. Dachen and Xiaomi are shareholders
php数组转化为xml
1036 Boys vs Girls
Keepalived installation, use and quick start
Generics and generic constraints of typescript
"Simple" infinite magic cube