On the ten new characteristics of Java8 __java8

Source: Internet
Author: User
Tags readable multiple inheritance in c google guava
This article will list the new Java8, and will use a simple code example to guide you through the use of default interface methods, lambda expressions, method references, and multiple annotation, and then you will learn the latest API improvements, such as streaming, functional interfaces, Map and the new date API

"Java is still not dead-and people are starting to figure."

This article will use a simple annotated code to describe the new feature, and you will not see the scary text.

The default method of an interface

Java 8 allows us to add a Non-abstract method implementation to the interface, just using the default keyword, which is called an extension method, as follows:
Copy code code as follows:
Interface Formula {
Double calculate (int a);

Default double sqrt (int a) {
Return Math.sqrt (a);
}
}
The formula interface defines the SQRT method in addition to the Calculate method, and implements a subclass of the formula interface to implement only one calculate method, and the default method sqrt will be used directly on the subclass.
Copy code code as follows:
Formula Formula = new Formula () {
@Override
public double Calculate (int a) {
return sqrt (A * 100);
}
};

Formula.calculate (100); 100.0
FORMULA.SQRT (16); 4.0
The formula in this article is implemented as an instance of an anonymous class, which is very easy to understand and 6 lines of code implement the computed sqrt (A * 100). In the next section, we'll see a simpler way to implement a single method interface.

Translator Note: In Java, only single inheritance, if you want to give a class A new attribute, usually by using an interface, which supports multiple inheritance in C + +, allows a subclass to have both the interface and the functionality of multiple parent classes, and in other languages, the method of having a class with other reusable code is called Mixin. This special new Java 8 is closer to Scala's trait in terms of compiler implementations. It is also known in C # as the concept of extension methods, allowing for existing type extension methods, which are semantically different from that of Java 8.

Second, LAMBDA expression

First look at how strings are arranged in the old version of Java:
Copy code code as follows:
list<string> names = Arrays.aslist ("Peter", "Anna", "Mike", "Xenia");

Collections.sort (names, new comparator<string> () {
@Override
public int Compare (string A, string b) {
Return B.compareto (a);
}
});
You only need to pass a list object to the static method Collections.sort and a comparer to arrange in the specified order. It is common practice to create an anonymous comparer object and pass it to the sort method.

In Java 8 You don't need to use this traditional way of anonymous objects, Java 8 provides a simpler syntax, lambda expression:
Copy code code as follows:
Collections.sort (names, (string A, string b)-> {
Return B.compareto (a);
});
See, the code becomes more and more readable, but it can actually be written a little shorter:
Copy code code as follows:
Collections.sort (names, (string A, string b)-> B.compareto (a));
For a function body with only one line of code, you can remove the curly braces {} and the return keyword, but you can write a little shorter:
Copy code code as follows:
Collections.sort (names, (A, B)-> B.compareto (a));
The Java compiler can automatically deduce parameter types, so you can not write again. Let's look at what the lambda expression can do to make things easier:

Third, function-type interface

How lambda expressions are represented in the Java type System. Each lambda expression corresponds to a type, usually the interface type. A "functional interface" refers to an interface that contains only an abstract method, and each lambda expression of that type is matched to this abstract method. Because the default method is not an abstract method, you can also add a default method to your functional interface.

We can use lambda expressions as any type of interface that contains only one abstract method, and make sure that your interface does that, and you just add @FunctionalInterface annotations to your interface. The compiler will make an error if it finds that there are more than one abstract method for the interface in which you have annotated the annotation.

Examples are as follows:
Copy code code as follows:
@FunctionalInterface
Interface Converter<f, t> {
T convert (F from);
}
converter<string, integer> Converter = (from)-> integer.valueof (from);
Integer converted = Converter.convert ("123");
System.out.println (converted); 123
Note that if @functionalinterface is not specified, the above code is also true.

The translator maps a lambda expression to a single method interface, which is implemented in a different language before Java 8, such as the Rhino JavaScript interpreter, if a function parameter receives a single method interface and you pass a Function,rhino The interpreter automatically makes a single interface instance to the function adapter, and the typical scenario has org.w3c.dom.events.EventTarget AddEventListener the second parameter eventlistener.

Iv. methods and constructor references

The code in the previous section can also be represented by a static method reference:
Copy code code as follows:
converter<string, integer> Converter = integer::valueof;
Integer converted = Converter.convert ("123");
System.out.println (converted); 123
Java 8 allows you to use:: Keyword to pass a method or constructor reference, the above code shows how to refer to a static method, we can also refer to the method of an object:
Copy code code as follows:
converter = Something::startswith;
String converted = Converter.convert ("Java");
System.out.println (converted); J
Next look at how the constructor uses:: Keyword to reference, first we define a simple class that contains multiple constructors:
Copy code code as follows:
Class Person {
String FirstName;
String LastName;

Person () {}

Person (string firstName, String lastName) {
This.firstname = FirstName;
This.lastname = LastName;
}
}
Next we specify an object factory interface to create the person object:
Copy code code as follows:
Interface Personfactory<p extends Person> {
P Create (String firstName, string lastName);
}
Here we use constructor references to correlate them, rather than implement a complete factory:
Copy code code as follows:
personfactory<person> personfactory = person::new;
Person person = personfactory.create ("Peter", "Parker");
We only need to use person::new to get a reference to the person class constructor, and the Java compiler automatically chooses the appropriate constructor based on the signature of the Personfactory.create method.

v. LAMBDA scope

The way in which you access an outer scope and an older version of an anonymous object in a lambda expression is similar. You can directly access the outer local variables marked final, or the fields of the instance and the static variables.

vi. accessing local variables

We can access the outer local variables directly in the lambda expression:
Copy code code as follows:
final int num = 1;
Converter<integer, string> stringconverter =
(from)-> string.valueof (from + num);

Stringconverter.convert (2); 3
But unlike an anonymous object, the variable num here can be no longer declared final, and the code is equally correct:
Copy code code as follows:
int num = 1;
Converter<integer, string> stringconverter =
(from)-> string.valueof (from + num);

Stringconverter.convert (2); 3
However, NUM must not be modified by the following code (that is, the implicit final semantics), for example:
Copy code code as follows:
int num = 1;
Converter<integer, string> stringconverter =
(from)-> string.valueof (from + num);
num = 3;
Attempting to modify num in a lambda expression is also not allowed.

Vii. accessing object fields and static variables

Unlike local variables, the fields within the lambda for instance and static variables are both readable and writable. This behavior is consistent with the anonymous object:
Copy code code as follows: Class Lambda4 {
static int outerstaticnum;
int outernum;

void Testscopes () {
Converter<integer, string> stringConverter1 = (from)-> {
Outernum = 23;
Return string.valueof (from);
};

Converter<integer, string> stringConverter2 = (from)-> {
Outerstaticnum = 72;
Return string.valueof (from);
};
}
}

the default method of accessing the interface

Remember the formula example in the first section, interface formula defines a default method sqrt can be accessed directly by an instance of formula, but this is not possible in lambda expressions.
The default method cannot be accessed in a lambda expression, the following code cannot be compiled:
Copy code code as follows:
Formula Formula = (a)-> sqrt (A * 100);
Built-in functional interfaces
The JDK 1.8 API contains a number of built-in functional interfaces that are commonly used in old Java, such as comparator or runnable interfaces, that add @functionalinterface annotations to use on a lambda.
The Java 8 API also offers a number of new functional interfaces to make work more convenient, with some interfaces coming from the Google Guava Library, and even if you're familiar with them, it's important to see how these extend to the lambda.

Predicate Interface

The predicate interface has only one parameter, which returns a Boolean type. The interface contains a variety of default methods to synthesize predicate groups into other complex logic (e.g., with, or, non):
Copy code code as follows:
predicate<string> predicate = (s)-> s.length () > 0;

Predicate.test ("foo"); True
Predicate.negate (). Test ("foo"); False

predicate<boolean> nonnull = objects::nonnull;
predicate<boolean> isNull = objects::isnull;

Predicate<string> isempty = String::isempty;
predicate<string> isnotempty = Isempty.negate ();

Function Interface

The function interface has a parameter and returns a result with some default methods that can be combined with other functions (compose, andthen):
Copy code code as follows:
function<string, integer> tointeger = integer::valueof;
function<string, string> backtostring = Tointeger.andthen (string::valueof);

Backtostring.apply ("123"); "123"

Supplier Interface

The Supplier interface returns an arbitrary value, and unlike a function interface, the interface has no parameters
Copy code code as follows:
supplier<person> personsupplier = person::new;
Personsupplier.get (); New person

Consumer Interface

The Consumer interface represents the execution of an operation on a single parameter.
Copy code code as follows:
consumer<person> greeter = (p)-> System.out.println ("Hello," + p.firstname);
Greeter.accept (New person ("Luke", "Skywalker"));

Comparator Interface

Comparator is a classic interface in old Java, where Java 8 adds a variety of default methods:
Copy code code as follows:
Comparator<person> Comparator = (P1, p2)-> p1.firstName.compareTo (p2.firstname);

person P1 = new Person ("John", "Doe");
person P2 = new Person ("Alice", "Wonderland");

Comparator.compare (P1, p2); > 0
Comparator.reversed (). Compare (P1, p2); < 0

Optional Interface

Optional is not a function is an interface, this is to prevent the nullpointerexception exception of the auxiliary type, this is the next session will be used in the important concept, now let's simply look at what this interface can do:

Optional is defined as a simple container whose value may be null or not NULL. Before Java 8, a function should normally return a Non-empty object but occasionally return null, whereas in Java 8 it is not recommended that you return NULL instead of returning to optional.
Copy code code as follows:
optional<string> Optional = Optional.of ("Bam");

Optional.ispresent (); True
Optional.get

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.