Java8 new Features-language new features

Source: Internet
Author: User

I. Lambda expressions and functional interfaces

It allows us to pass functions as arguments to a method, or to treat the code itself as data processing: Functional developers are very familiar with these concepts. Many of the languages on the JVM platform (Groovy, Scala, and so on) support lambda expressions from the date of birth, but Java developers have no choice but to use anonymous inner classes instead of lambda expressions.

The simplest lambda expression can consist of a comma-separated list of parameters, a symbol, and a statement block.


1.1. Expression syntax:

A lambda expression is used to represent a function, so it, like a function, has parameters, return values, body of functions, but it does not have a function name, so a lambda expression is equivalent to an anonymous function. The syntax is as follows:

Note 1: The type of the parameter in the above code is explicitly specified, but can also be inferred by the compiler, for example:

Arrays.aslist ("A", "B", "D"). ForEach (E-System.out.println (e));


NOTE 2: If a lambda expression requires a more complex statement block, you can surround the statement block with curly braces, similar to the body of a function in Java, for example:

Arrays.aslist ("A", "B", "D"). ForEach (E, {System.out.print (e); System.out.print (e);} );


Note 3:lambda expressions can refer to class members and local variables (which implicitly convert these variables to final), such as the following two blocks of code that have the exact same effect:

String separator = ",";  Arrays.aslist ("A", "B", "D"). ForEach ((String e), System.out.print (e + separator)), and final String separator = ","; Arrays.aslist ("A", "B", "D"). ForEach ((String e), System.out.print (e + separator));


1.2.lambda Expressions Use

For example, to filter person objects older than 10:


1.2.1. Defining a functional interface for a lambda expression

@FunctionalInterfaceinterface filterprocessor<t>{Boolean process (T t);}

Lambda designers have considered many ways to make existing functions well compatible with lambda expressions, resulting in the concept of functional interfaces. A function interface refers to an interface that has only one function, and such an interface can be implicitly converted to a lambda expression. Java.lang.Runnable and java.util.concurrent.Callable are the best examples of functional interfaces. In practice, the functional interface is very fragile: as long as a developer adds a function to the interface, the interface is no longer a functional interface and causes compilation to fail. To overcome this code-level fragility and to explicitly state that an interface is a functional interface, Java 8 provides a special annotation @functionalinterface (all the relevant interfaces in the Java library already have this annotation), and a simple function-type interface definition:

When defining a functional interface for a lambda expression, you need to add the annotation @functionalinterface, which can only have one abstract function. When the number of abstract functions in the interface is not 1 o'clock, an error message is indicated.

However, it is important to note that the default and static methods (which are said below) do not break the definition of a functional interface


1.2.2. Implementing Filter Functions

List<t> Filter (list<t> List, filterprocessor<t> filterprocessor) {list<t> result = new ArrayLis    T<t> ();    if (filterprocessor.process (t)) Result.add (t); return result;}


The filter function receives a functional interface, which is used to receive a lambda expression.


1.2.3. Passing a lambda expression

list<person> result = Filter (list, (person P)->p.getage () >10);


Simply pass the lambda expression as a parameter to the function interface of filter, so that the person object older than 10 years old can be obtained in result.


Second, the default method and static method of the interface

Java 8 uses two new concepts to extend the meaning of the interface: the default method and the static method.

1. The default method makes the interface somewhat similar to traits, but it does not achieve the same goal. The default method allows developers to add new methods to existing interfaces without breaking binary compatibility, i.e. not forcing classes that implement the interface to implement this new addition.

The difference between a default method and an abstract method is that the abstract method needs to be implemented, and the default method does not. The default method provided by the interface is inherited or overwrite by the implementation class of the interface

Another interesting feature of 2.Java 8 is the ability to define static methods in the interface, as shown in the example code:

Private interface Defaulablefactory {//Interfaces now allow static methods static defaulable Create (supplier& Lt    defaulable > Supplier) {return supplier.get (); }}

The implementation of the default method on the JVM provides support at the bytecode level and is therefore highly efficient. The default method allows the interface to be improved without breaking the existing inheritance system. The application of this feature in the official library is to add new methods to the Java.util.Collection interface, such as stream (), Parallelstream (), ForEach (), and Removeif (), and so on.


Although the default method has so many benefits, it should be used sparingly in practical development: in complex inheritance systems, the default method can cause ambiguity and compilation errors.


Third, method reference

Method references allow developers to directly reference existing methods, Java class construction methods, or instance objects. Method references are used in conjunction with lambda expressions, making the Java class construction method look compact and concise, with no complex template code.

In the following example, the car class is an example of a different method reference, which helps the reader distinguish between four types of method references.

Public static class car {    public static car create (  final Supplier< Car > supplier )  {         return supplier.get ();    }                   public static void  Collide ( final Car car )  {         System.out.println (  "collided "  + car.tostring ()  );    }     public void follow ( final Car another )  {         system.out.println (  "following the "  +  Another.tostring ()  );     }    public void repair ()  {        &Nbsp;  system.out.println (  "repaired "  + this.tostring ()  );     }}

The first method refers to a type that is a constructor reference, a syntax of class::new, or a more general form: Class<t>::new. Note: This constructor has no parameters.

Final Car car = car.create (car::new), final list< Car > cars = arrays.aslist (car);


The second method refers to a type that is a static method reference, and the syntax is Class::static_method. Note: This method accepts parameters for a car type.

Cars.foreach (Car::collide);


The third method refers to a type that is a reference to a member method of a class, the syntax is Class::method, and note that this method does not define an entry:

Cars.foreach (Car::repair);


The fourth method refers to a type that is a reference to a member method of an instance object, and the syntax is Instance::method. Note: This method accepts parameters for a car type:

Final Car police = car.create (car::new); Cars.foreach (Police::follow);


Iv. Repetition of annotations

Since the introduction of annotations in Java 5, this feature has become very popular and is widely used in various frameworks and projects. However, there is a big limitation of annotations: You cannot use the same annotation multiple times in the same place. Java 8 breaks This limitation by introducing the concept of repeating annotations, allowing the same annotation to be used multiple times in the same place.


In Java 8, using @repeatable annotations to define duplicate annotations, in fact, is not a language-level improvement, but rather a compiler-made trick, the underlying technology is still the same.

V. Better type inference

The Java 8 compiler has a big boost in type inference, and in many scenarios the compiler can push the data type of a parameter to make the code more concise.

VI. application Scenarios for broadening annotations

Java 8 broadens the application scenario for annotations. Annotations can now be used on almost any element: local variables, interface types, superclass, and interface implementation classes, and can even be used on the exception definitions of functions.



Java8 new Features-language new features

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.