Please read my introduction to Java 8. This guide will step through all the new language features to guide you through Java 8. With the help of the short sample code, you will learn how to use the default interface methods, lambda expressions, method references, and repeatable annotations.
At the end of the article, you will be familiar with the latest API changes, such as streams, functional interfaces, map extensions, and new Date APIs.
There is not too much text-just some code snippets with annotations. Enjoy it together. the default method for the interface
Java 8 enables us to add a Non-abstract method implementation to an interface using the default keyword. This feature is also called the extension method (Extension Methods). As shown in the following example:
Interface Formula {
double calculate (int a);
Default double sqrt (int a) {return
math.sqrt (a);
}
}
In addition to the abstract method calculate, the interface Formula also defines the default method sqrt. The concrete class only needs to implement the abstract method calculate. The default method sqrt can be "out-of-the-box" when it is not implemented.
Formula Formula = new Formula () {
@Override public
double Calculate (int a) {return
sqrt (A *);
}
};
Formula.calculate (m); 100.0
formula.sqrt (); 4.0
Formula is created like an anonymous object. The code looks verbose: It takes 6 lines to calculate a simple sqrt (A * 100). As we'll see in the next section, the implementation of classes with only one method is a better approach in Java 8. lambda expression
Let's start with a simple example: how to sort a string list in the previous version of Java:
List names = Arrays.aslist ("Peter", "Anna", "Mike", "Xenia");
Collections.sort (names, new Comparator () {
@Override public
int Compare (string A, string b) {
return B.compareto (a);
}
});
The static method Collections.sort accepts a list and comparison method to sort the given list element. You will always find that you need to create anonymous comparison methods and pass them to the sorting method.
Unlike creating anonymous objects all day long, Java 8 has a short, much syntax: lambda expression:
Collections.sort (names, (string A, string b)-> {return
b.compareto (a);
});
As you can see, the code is shorter and easier to read, and it's shorter: