Take a look at the new features of Java8, write down notes,
1. Added optional,
This is the guava inside, and now java8 inside support, optional is used to deal with the null value.
Usage basic and guava inside the same,
Public Static void Main (string[] args) { Optional<String> str = optional.of ("abc"); System.out.println (Str.ispresent ()); System.out.println (Str.get ()); = optional.empty (); System.out.println (Str.ispresent ()); System.out.println (Str.orelse ("ABCD"));
The output value is:
True
Abc
False
Abcd
When there is a value in it, the use of OrElse will get the original value, such as when
optional<string> str = optional.of ("abc"); System.out.println (Str.orelse ("123"));
Then the output is ABC
2. The default method can be added to the interface, as shown below
Public Interface Formula { double calculate (int a); /** * JAVA8 new feature interface can add the default method, also known as extension method, implement this interface, do not need to override the default method , you can directly use @param a @return */ default double sqrt (int a) { return math.sqrt (a);} }
The default method can be implemented, you need to use default keyword
Classes that implement this interface do not need to override the default method
[Email protected] annotations,
The interface marked with this annotation is considered to be a function interface, that is, there is only one abstract method (the default method is not an abstract method), and when there are multiple abstract methods, a compilation error message appears.
4.lambda expression, this is a change that many people know
Lambda expressions can be used when implementing a functional interface
Such as
New Comparator<string>() { @Override publicint Compare (String A, string b) { return B.compareto (a); } { return B.compareto ( a); B.compareto (a));
The above four formulations are equivalent
The basic form of the lambda expression is (), {}
When the entire implementation is written in one line, the parentheses and the return keyword can be removed, and () The parameters are omitted, and the parameter types
5. References to methods and constructors
Example:
Public classPerson {PrivateString FirstName; PrivateString LastName; Person () {} person (string firstName, String listname) { This. FirstName =FirstName; This. LastName =ListName; } PublicString Getfirstname () {returnFirstName; } PublicString Getlastname () {returnLastName; } Public Static voidMain (string[] args) {personfactory<Person> factory = Person::New; Person Person= Factory.createperson ("Luo", "Lei"); System.out.println (Person.getfirstname ()+" "+person.getlastname ()); }}
Public Interface extends Person> { T Createperson (String firstName, String lastName);}
Use:: keyword, you can refer to a method or constructor, this interface can only be a functional interface
Of course Java8 also added some interfaces, and other features that I didn't read
The new features of Java8 are recorded here.
Java8 new Features