当前位置:网站首页>Lambda learning records
Lambda learning records
2022-06-10 23:55:00 【Li_ XiaoJin】
It mainly introduces how to build Lambda, Where it is used , And how to use it to make the code more concise .
Lambda—— Anonymous functions
Except for permission ( name ) Function becomes an equivalent ,Java 8 It also embodies the idea of taking function as value in a broader sense , Include Lambda( Or anonymous functions ).
* Behavior parameterization , It's a method that accepts multiple different behaviors as parameters , And use them internally , Ability to perform different behaviors .
* Behavior parameterization allows code to better adapt to changing requirements , Reduce future workload .
* Passing code , Is to pass the new behavior as a parameter to the method . But in Java 8 It's a long winded realization before . Verbose code caused by declaring many entity classes only once for an interface , stay Java 8 Previously, anonymous classes could be used to reduce .
* Java API There are many ways to parameterize with different behaviors , Including sorting 、 Threads and GUI Handle .
How to build Lambda, Where it is used , And how to use it to make the code more concise .
Lambda To see only one spot
You can put Lambda Expressions are understood as a way to express transitive anonymous functions succinctly : It has no name , But it has a list of parameters 、 Function main body 、 Return type , There may also be a list of exceptions that can be thrown .
// Java8 The way I wrote it before
Comparator<Apple> weight = new Comparator<Apple>() {
@Override
public int compare(Apple o1, Apple o2) {
return o1.getWeight().compareTo(o2.getWeight());
}
};
// Lambda
Comparator<Apple> weight1 = (a1, a2) -> a1.getWeight().compareTo(a2.getWeight());
// Lambda
Comparator<Apple> weight2 = Comparator.comparing(Apple::getWeight);
* parameter list —— Here it uses Comparator in compare Method parameters , Two Apple.
* arrow —— arrow -> Compare the parameter list with Lambda The main body is separated .
* Lambda The main body —— Compare the two Apple Weight of . The expression is Lambda The return value of .
Java8 Effective in Lambda expression :
Lambda The basic grammar of is
(parameters) -> expression
or ( Notice the curly braces of the statement )
(parameters) -> {statements;}
According to the above grammar rules , Which of the following is not valid Lambda expression ? (1) ()-> {}(2) ()-> "Raoul"(3) ()-> {return "Mario"; }(4) (Integer i)-> return "Alan"+i;(5) (String s)-> {"IronMan"; } answer : Only 4 and 5 It's invalid Lambda.(1) This Lambda No parameters , And back to void. It's similar to the method where the subject is empty :publicvoid run() {}.(2) This Lambda No parameters , And back to String As an expression .(3) This Lambda No parameters , And back to String( Using explicit return statements ).(4) return It's a control flow statement . To make this Lambda It works , You need to make curly braces , As shown below :(Integer i)-> {return "Alan"+i; }.(5)“Iron Man” It's an expression , It's not a statement . To make this Lambda It works , You can remove curly braces and semicolons , As shown below :(String s)-> "Iron Man". Or if you like , You can use an explicit return statement , As shown below :(String s)->{return "IronMan"; }.
Lambda Example :
Where and how to use Lambda
Functional interface
public interface Predicate<T> {
boolean test(T t);
}
A functional interface is an interface that defines only one abstract method .
API Some other functional interfaces in , Such as Comparator and Runnable.
What can I do with a functional interface ?Lambda Expressions allow you to provide implementations of abstract methods of functional interfaces directly in the form of inline , And take the whole expression as an example of a functional interface ( say concretely , It is a concrete implementation example of functional interface ). You can do the same thing with anonymous inner classes , It's just clumsy : Need to provide an implementation , And then instantiate it directly inline .
public class Test {
public static void main(String[] args) {
// Use Lambda
Runnable r1 = () -> System.out.println("Hello World! 1");
// Using anonymous classes
Runnable r2 = new Runnable() {
@Override
public void run() {
System.out.println("Hello World! 2");
}
};
process(r1);
process(r2);
process(() -> System.out.println("Hello World! 3"));
}
public static void process(Runnable r) {
r.run();
}
}
Hello World! 1
Hello World! 2
Hello World! 3
Function Descriptor
The signature of abstract method of functional interface is basically Lambda Signature of expression . We call this abstract method function descriptors . for example ,Runnable An interface can be seen as one that accepts nothing and returns nothing (void) The signature of the function , Because it has only one called run Abstract method of , This method accepts nothing , Nothing back (void).
Java 8 The common functional interface in :
Lambda How expressions do type checking . This will be in 3.5 Section , How the compiler checks Lambda Valid in the given context . Now? , As long as you know Lambda An expression can be assigned to a variable , Or pass it to a method that accepts a functional interface as a parameter , Of course, this Lambda The signature of an expression is the same as the abstract method of a functional interface .
“ Why can I pass only when I need a functional interface Lambda Well ? ” The designers of the language have also considered other approaches , For example, to Java Add function type . But they chose the present way , Because this way is natural and can avoid language becoming more complex . Besides , majority Java Programmers are already familiar with the idea of an interface with an abstract method ( For example, event handling ).
Which of the following are used Lambda An efficient way to express ?
answer : Only 1 and 2 It works . The first example works , Because Lambda()-> {} With signature ()-> void, This sum Runnable Abstract methods in run Match the signature of . Please note that , Nothing will be done after this code runs , because Lambda It's empty. ! The second example also works . in fact ,fetch The return type of the method is Callable.Callable Basically, a method is defined , Signature is ()-> String, among T By String Instead of . because Lambda()-> "Trickyexample; -)" His signature is ()-> String, So in this context you can use Lambda. The third example doesn't work , because Lambda expression (Apple a)-> a.getWeight() His signature is (Apple)->Integer, This sum Predicate:(Apple)-> boolean As defined in test Methods have different signatures .
About @FunctionalInterface
If you go to see the new Java API, You will find that the functional interface has @FunctionalInterface This annotation is used to indicate that the interface will be designed as a functional interface .
If you use @FunctionalInterface An interface is defined , And it's not a functional interface , The compiler will return an error indicating the cause . for example , The error message may be “Multiple non-overriding abstract methods foundin interface Foo”, Indicates that there are multiple abstract methods . Please note that ,@FunctionalInter-face Not required , But for the interface designed for this , It's a good way to use it . It's like @Override The annotation representation has been rewritten .
You can think of it as a sign .
hold Lambda Put it into practice : Orbit execution mode
Resource processing ( For example, working with files or databases ) A common pattern is to open a resource , Do something about it , Then close the resource . This setting is always similar to the cleanup phase , And it will focus on the important code that executes the processing . This is called surround execution (execute around) Pattern .
for example , In the following code , What is highlighted is the template code needed to read a line from a file ( Notice that you used Java 7 With resources in try sentence , It has simplified the code , Because you don't need to explicitly close resources ):
public static String processFiles() {
try {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
return br.readLine();
}
}
Final effect :
Lambda It can only be used when the context is a functional interface .
- Create an interface , One can match BufferedReader-> String, You can also throw IOException Abnormal interface .
@FunctionalInterface public interface BufferReaderProcessor { String process(BufferedReader br) throws IOException; } - Make this interface new processFile Method parameters .
public static String processFiles(BufferReaderProcessor p) { try { BufferedReader br = new BufferedReader(new FileReader("data.txt")); return p.process(br); } }
whatever BufferedReader-> String Formal Lambda Can be passed as a parameter , Because they conform to BufferedReaderProcessor Defined in interface process Method signature .
Now there is only one way to do this processFile Execution within the main body Lambda The code represented .
please remember ,Lambda Expressions allow you to inline directly , Provides implementation for abstract methods of functional interfaces , And take the entire expression as an instance of a functional interface . therefore , Can be in processFile Within the subject , Yes, I got BufferedReaderProcessor Object call process Method to perform processing :
Now you can pass different Lambda reusing processFile Method , And deal with files in different ways .
// Deal with a line
String res1 = processFiles((BufferedReader br1) -> br1.readLine());
// Process two lines
String res2 = processFiles((br2) -> br2.readLine() + br2.readLine());
Using functional interfaces
Lambda And methods of quoting actual combat
- Using anonymous classes
- Use Lambda expression
Can continue to rewrite as :
Comparator It has a name called comparing The static auxiliary method of , It can accept a Function To extract Comparable Key value , And generate a Comparator object . Can be written as :
Use method reference
summary
- Lambda An expression can be understood as an anonymous function : It has no name , But there's a list of parameters 、 Function main body 、 Return type , There may also be a list of exceptions that can be thrown .
- Lambda Expressions let you pass code succinctly .
- A functional interface is an interface that simply declares an abstract method .
- It can only be used where a functional interface is accepted Lambda expression .
- Lambda Expressions allow you to inline directly , Provides implementation for abstract methods of functional interfaces , And take the entire expression as an instance of a functional interface .
- Java 8 With some common functional interfaces , Put it in java.util.function In the bag , Include Predicate、Function<T, R>、Supplier、Consumer and BinaryOperator.
- To avoid packing operations , Yes Predicate and Function<T, R> And so on general function type interface primitive type specialization :IntPredicate、IntToLongFunction etc. .
- Orbit execution mode ( That is, in the middle of the code necessary for the method , What do you need to do , Such as resource allocation and cleanup ) Can cooperate with Lambda Improve flexibility and reusability .
- Lambda The type that the expression needs to represent is called the target type .
- Method references let you reuse existing method implementations and pass them directly .
- Comparator、Predicate and Function There are several functional interfaces that can be used to combine Lambda The default method for expressions .
Copyright: use Creative Commons signature 4.0 International license agreement to license Links:https://lixj.fun/archives/lambda-learn-note
边栏推荐
- Is it safe to open an account in Shanghai Securities?
- LabVIEW用VISA Read函数来读取USB中断数据
- Why many new websites are not included by search engines
- HyperLeger Fabric安装
- It is known that the transverse grain pressure resistance of a certain wood obeys n (x, D2). Now ten specimens are tested for transverse grain pressure resistance, and the data are as follows: (unit:
- The serial port in the visa test panel under LabVIEW or max does not work
- 细数十大信息安全原则
- 干货丨MapReduce的工作流程是怎样的?
- 快速排序
- 示波器和频谱分析仪的区别
猜你喜欢

How to measure the refresh rate of oscilloscope

Solve access denied for user 'root' @ 'localhost' (using password: yes)

【Pygame小游戏】别找了,休闲游戏专题来了丨泡泡龙小程序——休闲游戏研发推荐

MySQL table mechanism

VS 番茄助手添加头注释 以及使用方式

Prefer "big and small weeks", only write 200 lines of code every day, and the monthly salary of 8k-17k people will rise again

怎么生成自动参考文献(简单 有图)

R language to draw two-dimensional normal distribution density surface;

It is known that the transverse grain pressure resistance of a certain wood obeys n (x, D2). Now ten specimens are tested for transverse grain pressure resistance, and the data are as follows: (unit:

HyperLeger Fabric安装
随机推荐
IGBT and third generation semiconductor SiC double pulse test scheme
R language to draw two-dimensional normal distribution density surface;
vtk.js中vtp下载
都说验证码是爬虫中的一道坎,看我只用五行代码就突破它。
示波器刷新率怎么测量
Difference between oscilloscope and spectrum analyzer
C# Tryparse的用法
Four ways to add names to threads in the thread pool
LabVIEW使用MathScript Node或MATLAB脚本时出现错误1046
黑马头条丨腾讯薪酬制度改革引争议;英特尔全国扩招女工程师;黑马100%就业真的吗......
Kubernetes 基本介绍及核心组件
Common settings for vs
OSS stores and exports related content
Hyperleger fabric installation
LabVIEW obtains the information of all points found by the clamp function
自制APP连接OneNET---实现数据监控和下发控制(MQTT)
关于优化API接口响应速度
LabVIEW phase locked loop (PLL)
Two debugging techniques in embedded software development
1. open the R program, and use the apply function to calculate the sum of 1 to 12 in the sequence of every 3 numbers. That is, calculate 1+4+7+10=? 2+5+8+11=?, 3+6+9+12=?