当前位置:网站首页>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
边栏推荐
- MySQL命令行导入导出数据
- 【Pygame小游戏】Chrome上的小恐龙竟可以用代码玩儿了?它看起来很好玩儿的样子~
- LabVIEW change the shape or color of point ROI overlay
- What Fiddler does for testing
- Four ways to add names to threads in the thread pool
- 判等问题:如何确定程序的判断是正确的?
- 2022 college entrance examination quantitative paper | please answer the questions for quantitative candidates
- Apple CMS collection station source code - building tutorial - attached source code - new source code - development documents
- 苹果CMS采集站源码-搭建教程-附带源码-全新源码-开发文档
- Simple impedance matching circuit and formula
猜你喜欢

300 questions on behalf of the first lecture on determinant
![[opencv practice] this seal](/img/f4/c6a4529b8b24773bcb39b4d2c6e16f.png)
[opencv practice] this seal "artifact" is awesome, saving time and improving efficiency. It is powerful ~ (complete source code attached)

csdn每日一练——有序表的折半查找

LabVIEW 禁止其他可多核心处理的应用程序在所有核心上执行

Error 1046 when LabVIEW uses MathScript node or matlab script

【Pygame小游戏】Chrome上的小恐龙竟可以用代码玩儿了?它看起来很好玩儿的样子~

LeetCode 501 :二叉搜索树中的众数

Basic introduction and core components of kubernetes

LabVIEW获取IMAQ Get Last Event坐标

LabVIEW用高速数据流盘
随机推荐
LabVIEW错误“内存已满 - 应用程序停止在节点”
csdn每日一练——有序表的折半查找
【LaTex】latex VS Code snippets(代码片段)
[untitled]
Difference between oscilloscope and spectrum analyzer
[new version] new pseudo personal homepage v2.0- starze V Club
Top ten information security principles
B 树的简单认识
【 pygame Games 】 don't find, Leisure Games Theme come 丨 Bubble Dragon applet - - Leisure Games Development recommendation
Leetcode 501: mode dans l'arbre de recherche binaire
The serial port in the visa test panel under LabVIEW or max does not work
Data and information resource sharing platform (VIII)
curl导入postman报错小记
BGP - route map extension (explanation + configuration)
Unity 脚本无法显示C#源码的中文注释 或者VS创建的脚本没有C#源码的注释
示波器刷新率怎么测量
LabVIEW锁相环(PLL)
LeetCode 501 :二叉搜索樹中的眾數
Lambda 学习记录
C# Tryparse的用法