PDF Document Uploaded Github
Github:https://github.com/zwjlpeng/Angrily_Learn_Java_8
Chapter one Lambda
1.1 introduction
The textbook says there are two modes of programming , Process oriented programming and object oriented programming , In fact, there was function oriented programming before object-oriented programming ( Functional programming ) , It used to be ignored 、 Don’t be seriously , Now from academia to business , Support for functional programming languages currently has Scala、Erlang、F#、Python、Php、Java、Javascript etc. , Some say it’s going to be the next mainstream in programming languages …
1.2 Lambda expression
Why Lambda expression ?
1. Use Lambda Expressions can make code more compact , For example, in Java To implement a thread , Output only one string Hello World!, Our code is as follows :
public static void main(String[] args) throws Exception {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello World!");
}
}).start();
TimeUnit.SECONDS.sleep(1000);
}
Use Lambda After the expression, the code becomes the following form :
public static void main(String[] args) throws Exception {
new Thread(() -> System.out.println("Hello World!")).start();
TimeUnit.SECONDS.sleep(1000);
}
Is the code becoming more compact ~, Others, such as various monitors , And event handlers can be simplified in this way .
2. The ability to modify methods , In fact, it’s plain , That is, a function can accept parameters with a function as a unit , stay C/C++ In this case, the function pointer , stay Java The middle is Lambda expression , For example, in Java Use set classes to sort a string in a dictionary sequence , The code is as follows :
public static void main(String[] args) {
String []datas = new String[] {"peng","zhao","li"};
Arrays.sort(datas);
Stream.of(datas).forEach(param -> System.out.println(param));
}
In the above code Arrays Inside sort Method , Now we don’t need to sort by Dictionary , It’s sort by the length of the string , The code is as follows :
public static void main(String[] args) {
String []datas = new String[] {"peng","zhao","li"};
Arrays.sort(datas,(v1 , v2) -> Integer.compare(v1.length(), v2.length()));
Stream.of(datas).forEach(param -> System.out.println(param));
}
Is it convenient , We don’t need to achieve Comparable Interface , Use one Lambda Expression can change the shape of a function to ~
1.3 Syntax
1.Lambda The formal representation of the expression is as follows
Parameters -> an expression
2. If Lambda Multiple statement blocks are executed in the expression , Multiple statement blocks need to be added to {} For packaging , If there is a return value , Need to show the specified return sentence , As shown below :
Parameters -> {expressions;};
3. If Lambda Expressions don’t need arguments , You can use an empty bracket to indicate , The following example shows
() -> {for (int i = 0; i < 1000; i++) doSomething();};
4.Java It’s a strongly typed language , So parameters have to be typed , If the compiler can infer Lambda The argument type of the expression , You don’t need to specify what we show , As shown below , stay Java It is speculated that Lambda The parameter types of expressions are basically similar to the methods of inferring generic types , as for Java How to deal with generics , Omitted here
String []datas = new String[] {"peng","zhao","li"};
Arrays.sort(datas,(String v1, String v2) -> Integer.compare(v1.length(), v2.length()));
In the above code The display specifies the parameter type Stirng, Actually, it doesn’t specify , As shown in the following code , It’s OK, too , Because the compiler will be based on Lambda The functional interface corresponding to the expression Comparator<String> Make automatic inference
String []datas = new String[] {"peng","zhao","li"};;
Arrays.sort(datas,(v1, v2) -> Integer.compare(v1.length(), v2.length()));
5. If Lambda The expression has only one parameter , And the type of the parameter can be inferred by the compiler , Can be used as follows Lambda expression , That is, you can omit the type of parameter and bracket
Stream.of(datas).forEach(param -> {System.out.println(param.length());});
6.Lambda The return type of the expression , Do not need to specify , The compiler will infer , It’s self inference
7.Lambda The parameters of the expression can use modifiers and annotations , Such as final、@NonNull etc.
1.4 Functional interface
The functional interface is Java 8 For support Lambda Expression is a new invention , What’s mentioned above Lambda Syntax As mentioned in sort The sorting method is an example , A functional interface is used in this sort method , The prototype declaration of the function is as follows
public static <T> void sort(T[] a, Comparator<? super T> c)
In the above code Comparator<? Super T> It’s a functional interface ,? Super T or ? entends T from Java 5 Start introducing… When generics are supported , You have to understand , Let’s not talk about
What is a functional interface
1. Functional interfaces have two main features , It’s an interface , This interface has a unique extraction method , We call interfaces that satisfy these two characteristics functional interfaces , Speaking of this , I have to say that there is a specific implementation problem in the interface ~
2.Lambda An expression cannot exist without the target type , This directory type is a functional interface , Here is an example
String []datas = new String[] {"peng","zhao","li"};
Comparator<String> comp = (v1,v2) -> Integer.compare(v1.length(), v2.length());
Arrays.sort(datas,comp);
Stream.of(datas).forEach(param -> {System.out.println(param);});
Lambda The expression is assigned to comp Function interface variables
3. Functional interfaces can be used @FunctionalInterface Annotate , After using this annotation , There are two main advantages , The compiler knows that this is a functional interface , Meet the requirements of functional expression , The other is generation Java Doc It is explicitly annotated
4. abnormal , If Lambda Expressions throw non runtime exceptions , The functional interface also needs to throw an exception , To put it bluntly , In a word , The functional interface is Lambda The target type of the expression
5. Functional interfaces can define public static Method , Think about it Java We provide Collection Interface , There is also a Collections Tools, etc , stay Java It’s just Collections The implementation of is transferred to the interface , But for backward compatibility , The old one Collection/Collections And so on
6. The functional interface can provide multiple image extraction methods , what ! It says there can only be one ? Yes , Multiple image extraction methods can be provided in the functional interface , But these methods limit the scope , Can only be Object Existing methods in types , Why do this ? Here to ignore , You can study it yourself
7. The default implementation of methods can be defined in functional interfaces , Here is Predicate Class code , Not only can it provide a default Realization , And it can provide multiple default To achieve? ,Java 8 It used to be OK ? My friends and I are shocked , This leads to the problem of multiple inheritance , Want to know Java 8 How to deal with it , Actually Easy, I’ll talk about it later ~
8. Why provide default Interface implementation ? Here’s a default implementation
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
Java 8 This function is implemented by default in the interface , In fact, in a large number of programs, it violates the abstract feature of the interface , increase default The main reason for implementation is to consider compatibility and the cost of code change , for example , stay Java 8 To the iterator This interface adds a method , Then all classes that implement this interface need to implement this method once , that Java 8 Too many classes need to be changed , So in Iterator Add one to the interface default Realization , Then all classes that implement this interface have this implementation , To put it bluntly , It’s just a template design pattern
1.5 Method reference
Sometimes , The code we need to execute already exists in some classes , There’s no need for us to write Lambda expression , You can use this method directly , This is what we call method reference , As shown below , Code before using method reference
As shown below
Stream.of(datas).forEach(param -> {System.out.println(param);});
The code after using the method reference is as follows
Stream.of(datas).forEach(System.out::println);
The above example uses out object , The following example uses the static method reference of the class to sort the elements in the string array regardless of case
String []datas = new String[] {"peng","Zhao","li"};
Arrays.sort(datas,String::compareToIgnoreCase);
Stream.of(datas).forEach(System.out::println);
Above are some typical examples of method references
Specific classification of method references
Object:instanceMethod
Class:staticMethod
Class:instanceMethod
The first two of the above categories are in Lambda Expressions are equivalent in the sense of , Pass parameters to methods , Example above
System.out::println == x -> System.out.println(x)
The last category , The first parameter is the target of the method execution , The following example
String::compareToIgnoreCase == (x,y) -> x.compareToIgnoreCase(y)
And something like that super::instanceMethod This method is essentially the same as Object::instanceMethod similar
1.6 Construction method reference
Constructing method references is similar to method references , Except for one thing. , The method of constructing method reference is new! Here are two examples
Example 1 :
String str = "test";
Stream.of(str).map(String::new).peek(System.out::println).findFirst();
Example 2 :
String []copyDatas = Stream.of(datas).toArray(String[]::new);
Stream.of(copyDatas).forEach(x -> System.out.println(x));
To sum up , There are two forms of constructor references
Class::new
Class[]::new
1.7 Lambda Expression scope
On the whole ,Lambda The variable scope of an expression is very similar to that of an inner class , It’s just that the conditions are relatively , Relax some of the previous internal class to refer to the variables of the external class , It has to be like this
final String[] datas = new String[] { "peng", "Zhao", "li" };
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(datas);
}
}).start();
Declare variable as final Type of , Now in Java 8 You can write code like this in
String []datas = new String[] {"peng","Zhao","li"};
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(datas);
}
}).start();
You can also write like this
new Thread(() -> System.out.println(datas)).start();
Anyway, how do you like to write , Just write about it ,I don’t Care it!
Looking at the two pieces of code above , Can find a significant difference , Namely Java 8 Middle inner class or Lambda Expression references to external variables are relaxed , It’s not mandatory to add final Keyword. , however Java 8 The variable is required to be effectively final
What is effectively final?
Effectively final Is a valid read-only variable , It means that this variable can be omitted final keyword , But this variable must be read-only , That is, once defined , You can’t modify it later , The following code will compile incorrectly
String []datas = new String[] {"peng","Zhao","li"};
datas = null;
new Thread(() -> System.out.println(datas)).start();
Java The inner classes in and Lambda It is also not allowed to modify variables in external classes in expressions , This is to avoid multithreading race condition
Lambda Variables and this keyword
Lambda The variable defined in is the same scope as the variable in the outer class , That is, the outer class defines ,Lambda You can’t repeat the definition , At the same time Lambda The expression uses this keyword , Pointing to an external class , You can practice it yourself , Here slightly
Unfinished to be written ….
Anger learning Java8 A series of :Lambda More articles on expressions
- Java8 series ( One ) Lambda expression
Functional programming Introducing Lambda Before expression , First, we need to introduce another concept , Functional programming . Functional programming is a programming paradigm , That is, the methodology of how to write programs . Its core idea is to write the operation process as a series of nested function calls as much as possible , Pay attention to the …
- Java8 Learning notes —-Lambda expression ( turn )
Java8 Learning notes —-Lambda expression Tianjin 2014-03-24 16:43:30 Published in :ATA The home of This paper mainly records my study Java8 History , It’s convenient for you to discuss and write your own notes together . Because I …
- Java8 New characteristics -Lambda What is an expression ?
Catalog Preface Anonymous inner class Functional interface and Lambda Expression syntax Implement functional interfaces and use Lambda expression : therefore Lambda What is an expression ? Actual combat application summary Preface Java8 New characteristics -Lambda expression , good …
- Happy bytes -Java8 New characteristics -Lambda expression
Last article we learned about Java8 New characteristics – Interface default method , Let’s talk next Java8 The new features Lambda expression . Lambda expression ( Also known as closures ), It allows us to pass a function as an argument to a method , Or think of the code itself as …
- Java8 New characteristics – Lambda expression – Basic knowledge
A lambda expression is an unnamed block of code (or an unnamed function) with a list of formal param …
- JAVA8 Study —— Explain profound theories in simple language Lambda expression ( The learning process )
JAVA8 Study — Explain profound theories in simple language Lambda expression ( The learning process ) lambda expression : Why do we use lambda expression stay JAVA in , We can’t pass a function as an argument to a method , You cannot declare a method that returns a function . stay …
- java8 New characteristics ——Lambda expression
The above is a brief introduction java8 We need some new features , And advantages , Also for this study java8 New features set a learning direction , The next few articles will learn one by one according to the new features mentioned above . This article starts from java8 The more important of the new features Lambda The expression opens …
- java8 learning Lambda Expression depth and flow preliminary
Lambda The expression goes deep : Last time [http://www.cnblogs.com/webor2006/p/8135873.html] Described in the Lambda The function of an expression is , It’s about this : As the red mark says , since …
- java8 learning Lambda Expression and functional interface
about Java8 In fact, compared with the previous version, the content added is quite a lot , There’s a lot of it about Lambda The expression and Stream API, These two parts are closely combined and cannot be treated separately , But it can be used alone , So from learning …
Random recommendation
- Xcode modify storyboard size
1: 2:
- 21.TFS File system building notes
TFS File system building notes Reference address : https://github.com/alibaba/tfs/blob/master/INSTALL.md https://github.com/alibaba/t …
- 2.1 Sequence containers -vector
vector 1) * : Use vector Must contain vector The header file . Variable length dynamic arrays , Support random access , all STL Algorithms can be used to vector To operate . ** : The time to randomly access an element by subscript is a constant …
- C# – Things roll back
This function depends on dbhelp.cs Portal :http://www.cnblogs.com/CyLee/p/5324652.html The starting point , Can’t put try In the sentence this.DbHelp.BeginTrans …
- C# Regular expressions and common regular expressions
Metacharacters describe . spot Match any single character . For example, regular expressions r.t Match these strings :rat.rut.r t, But it doesn’t match root. $ Match line terminator . For example, regular expressions weasel$ Can match string “He’ …
- ASP.NET Use System.Web.Script.Serialization analysis JSON ( turn )
JSON(JavaScript Object Notation) Is a lightweight data exchange format . Easy to read and write . At the same time, it is also easy for machine analysis and generation . It’s based on JavaScript Programming Langu …
- AI I’m sorry I still love you
Allen iverson , I’m sorry , I still love you . Sometimes I don’t know what happened to me , It wasn’t until the end that I found out , I still love you . That day , I know you , It’s out of control . These days , Thank you , It seems that because of your influence, I have changed , A lot of it . It is only until now that I have found that …
- solve error104 connection reset by peer;socket error problem
There are two reasons for this problem : 1. Because you visit the website too many times , So it’s forbidden by the webmaster . resolvent : 1. extend time.sleep Time 2. Setting agent 2. There is no such website at all .( Open the link and check !!!)
- lxml A concise tutorial
I’m going to be a wechat crawler recently , Before I wrote a little thing, I just used regular to extract data , If you need more stable data extraction , Or use xpath Positioning elements are more reliable . Weekend is fine , From the perspective of reptiles python xml Related libraries . P …
- noip Hierarchical number theory ?
TAT fast noip I started to contact number theory when I was young ( I really dare not learn ..) Let’s do some tidying up here ( It’s all definitions and stuff = =) Euclid :gcd(a,b)=gcd(b,a%b); See Encyclopedia for specific proof ? Expand Euclid : seek a*x+b*y …