Upgrading to Java 8, upgradingtojava

Source: Internet
Author: User

Upgrading to Java 8, upgradingtojava

Chapter 1 Lambda expressions

Lamada expressions are the most important new features in Java SE 8 and have long been regarded as missing features in Java. Their appearance makes the entire java language complete.
At least until now, you will learn what lambda is and why it is a great part in this section. New technologies such as single abstract methods and functional interfaces will also be introduced.

Why is it a lambda expression.

Like closures, Lambda expressions make some structures concise and readable, especially when dealing with internal classes. The following example shows a code block implemented by an internal class:

Runnable runnable = new Runnable (){

@ Override public void run (){

System. out. println ("Running ...");

}

}

In fact, the code can be replaced with the following short code with a Lambda expression:

Runnable runnable = ()-> System. out. println ("Running ...")

In other words, if you need to pass a runnable interface to java. util. concurrent. Executor class, you need

Executor.exe cute (new Runnable (){

@ Override

Public void run (){

System. out. println ("Running ...");

}

});

However, you can use Lambda expressions to achieve the same effect. Use the following code;

Executor.exe cute ()-> System. out. println ("Running ..."));

Short, elegant, clean, more expressive.

Modify the interface.

Before going into lambda, let's first introduce the defalut and static methods that can be included in java 8 interfaces. This part explains the static and defalut methods,
Why does lambda need to be significantly modified to integrate into the java core library.

Default Method

Adding a function to an interface is a secure way to extend the interface. However, you will eventually get two interfaces with similar functions. If you only need to inherit one or two interfaces, it is acceptable,
However, if you need to add new features to hundreds of interfaces, this becomes a serious problem.

This is exactly what Java designers are facing. They try to add lambda to Java 8 to support dozens of interfaces in the Collection framework. These interfaces need to add new methods to support Lambda. However, all interfaces that are extended only generate one-time interfaces, some of which may be named as List2 or ExtendeSet.

Instead, they solved the problem by adding the default method. The default method is the method that has been implemented in the interface. You do not need to implement the default method for an interface implementation class,
This means that adding a new method does not break the backward compatibility issue in the interface.

Define the default method in the interface. You only need to add the "default" keyword before the method signature. In addition, add braces and add code in them.

As you can learn later, many interfaces in Java 8 have default methods.

When you implement interfaces with default methods, you have these options:
Ignore the default methods and inherit them directly.
Redeclare the default method and change it to an abstract method.
Reload the default method.

Remember that java supports the default method mainly for backward compatibility. You should never write programs without classes.

Static method.

A static method is shared by all instances of the class. After Java 8, you can use static methods in the interface so that all static methods associated with the interface can use interfaces instead of a helper class.

The signature of the static method is similar to that of the default method. Instead of the default keyword, the static keyword is used. The static keyword is public by default in the interface.

Static methods are rare in Interfaces. In the java. util package, there are nearly 30 interfaces, and only two have static methods.

Functional Interface

In addition to the default and static methods, there is also a prerequisite before learning lambda: functional interfaces. A functional interface has only one abstract method and does not overwrite the methods in the Object class. It is also called a single abstract method (SAM ),

Java. lang. runnable is a functional interface, which has only one abstract method run (). functional interfaces can have default and static methods, the public method in the Object class is also a functional interface.

public interface Calculator {    double calculate(int a, int b);        public default int subtract(int a, int b) {        return a - b;    }    public default int add(int a, int b) {        return a * b;    }        @Override    public String toString();}

Common functional interfaces in the Java core library include: java. lang. runnable, java. lang. autoCloseable, java. lang. comparable, java. util. comparator. in addition, in java. util. there are also many functions.

Function interfaces can be marked with annotation @ FunctionalInterface.

Why are functional interfaces so important? You can use function interfaces to replace anonymous internal classes. If not, it cannot be used.

Lambda expression syntax

In the preceding example, the calculate method can be considered as the most basic lambda expression syntax. This method allows you to define any mathematical computation and return a double type using two integer parameters. There are two examples below.

Calculator addition = (int a, int b) -> (a + b);
System.out.println(addition.calculate(5, 20)); // prints 25.0

Calculator division  = (int a, int b) -> (double) a / b;
System.out.println(division.calculate(5, 2)); // prints 2.5

 

 

 

Lambda expressions are so elegant. How much code should you write without them?

There are two standard definitions of Lambda expressions:

(parameter list) -> expression

Or

(parameter list) -> {     statements}The parameter type is the same as that of the abstract method in the interface. However, the parameter type is optional. In other words, the following method is valid.
Calculator addition = (int a, int b) -> (a + b);
Calculator addition = (a, b) -> (a + b);
To sum up, Lambda expressions are shortcuts implemented by functions. They are equivalent to instances implemented by functional interfaces, because objects can be used as parameters in methods, therefore, it is also possible to use a Lambda expression as a method parameter.

Pre-defined functional interfaces in Java
Java. util. function is a new package in java 8. It contains more than 40 predefined functional interfaces for you to easily write code in the Lambda expression style. Below are some common interfaces.


Functional Interface Description
Function Pass a parameter to return a result. The result type can be different from the parameter type.
BiFunction Pass two parameters to return a result. The result type can be different from that of any parameter.
UnaryOperator The operation that represents an operator. Its return result type is the same as that of the operator. In fact, it can be regarded as a Function. It returns the same result as a parameter. It is a sub-interface of the Function.
BiOperator The operation of two operators. The return result type must be the same as that of the operator.
Predicate Pass a parameter and return a boolean Value Based on the parameter value.
Supplier Represents the result of a supplier.
Consumer A parameter is passed but no return value is returned.









Function, BiFunction and Other Variants
The Function interface is usually used to create a Parameter Function and return a result. It is a parameterized type and is defined as follows:
public interface Function<T, R>
T is the parameter type, and R is the returned result type.
Function has only one abstract method, and its signature is as follows:
R apply(T argument)
This method needs to be rewritten when the Function is used, the following example defines a Function to implement the conversion between the English meter and the kilometer. Function transmits an Integer type as a parameter and returns the Double type.

public class FunctionDemo1 {
    public static void main(String[] args) {
        Function<Integer, Double> milesToKms =
                (input) -> 1.6 * input;
        int miles = 3;
        double kms = milesToKms.apply(miles);
        System.out.printf("%d miles = %3.2f kilometers\n",
                miles, kms);
    }

}















Run this class and output it on the console:3 miles = 4.80 kilometers





















 

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.