Document new features of the Java 8 language

After reading kotlin's functions, function types, Lambda expressions, and then look at the new language features of JAVA 8 or vice versa, it will be interesting to combine them.

The following is mainly to record the new language features of Java 8:

Reference: https://docs.oracle.com/javase/8/docs/technotes/guides/language/enhancements.html

Lambda expression and Functional interface

To put it simply, the lambda expressions mentioned in programming are usually used when a function is needed, but you don't want to bother to name a function, that is, anonymous functions.
Lambda allows functions to be used as parameters of a method (functions are passed into methods as parameters). A lambda can be represented by a comma-separated list of parameters, a –> symbol and a function body. Lambdas can refer to member variables and local variables of a class (if these variables are not final, they will be implicitly converted to final, which is more efficient). Lambda may return a value. The type of the return value is also inferred by the compiler. If the body of the lambda is only one line, then there is no need to explicitly use the return statement.

E.g:

( String e ) -> {System.out.println( e );}
A functional interface is a normal interface with one method. Interfaces like this can be implicitly converted to lambda expressions. java.lang.Runnable and java.util.concurrent.Callable are the two most typical examples of functional interfaces. In practice, functional interfaces are error-prone: if someone adds another method to the interface definition, the interface is no longer functional, and the compilation process fails. In order to overcome this fragility of functional interfaces and to be able to explicitly declare the intent of an interface as a functional interface, Java 8 adds a special annotation @FunctionalInterface (all existing interfaces in the class library in Java 8 add the @FunctionalInterface annotation ).
E.g:
@FunctionalInterface
public interface Functional {
    void method();
}

Default and static methods of interfaces

Java 8 extends interface declarations with two new concepts, default methods and static methods.
Default methods make interfaces a bit like Traits (traits in Scala are similar to Interfaces in Java, but can contain implementation code.
For example:
private interface Defaulable {
    // Implementing classes can override this method
    default String notRequired() {
        return "Default implementation";
    }        
}
Another feature brought by Java 8 is that interfaces can declare (and provide implementations) static methods.

E.g:

interface DefaulableFactory {
    // Interfaces allow static methods
    static Defaulable create( Supplier< Defaulable > supplier ) {
        return supplier.get();
    }
}

method reference

Types of method references:

  1. referencing static methods
  2. An instance method that references a specific object
  3. Methods that refer to arbitrary objects of a specific class
  4. reference constructor
To refer to a static method, the syntax is Class::static_method,

E.g:

public class Person {
	public static int compareByAge(Person a, Person b) {
        return a.birthday.compareTo(b.birthday);
    }
]

// static method reference
Person::compareByAge
Refers to an instance method of a specific object, syntax: containingObject::instanceMethodName

E.g:

class ComparisonProvider {
    public int compareByName(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
}
// The JRE compiler infers the type parameter example table, in this example the parameter is (Person, Person)
ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);
A method that refers to an arbitrary object of a specific class, syntax: ContainingType::methodName

E.g:

// The following method references the lambda expression equivalent to the example String::compareToIgnoreCase: (String a, String b) -> a.compareToIgnoreCase(b).
// Parameters a, b are arbitrarily named for the purpose of illustrating the following example.
String[] stringArray = { "Barbara", "James", "Mary", "John",
    "Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);
Reference constructor, syntax Class::new

E.g:

    public static Car create( final Supplier< Car > supplier ) {
        return supplier.get();
    }

    // Call the method with a lambda expression:
    Car newCar = Car.create(() -> {return new Car();});
	
    // replace lambda expression with constructor reference
    Car newCar = Car.create(Car::new);

Duplicate annotations, expanding the context of the annotation

A limitation of using annotations before JAVA 8 is that the same annotation can only be declared once at the same location, not multiple times. Java 8 breaks this rule and introduces the duplicate annotation mechanism, so that the same annotation can be declared multiple times in the same place. The repeat annotation mechanism itself must be annotated with @Repeatable. Java 8 extends the context of annotations. You can now annotate almost anything: local variables, generic classes, implementations of superclasses and interfaces, even method exceptions.

Improvements in inferring generic type parameter inference from context

E.g:
List<String> stringList = new ArrayList<>();
stringList.add("A");
stringList.addAll(Arrays.asList());

// Java 7 needs to be written as:
List<String> stringList = new ArrayList<>();
stringList.add("A");
stringList.addAll(Arrays.<String>asList());
The purpose is to learn and communicate, the level is limited, please leave a message to point out any mistakes or impreciseness, I would be very grateful.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325916009&siteId=291194637