This article has been published on Github /JavaMap. It contains a series of articles on advanced technology knowledge for Java programmers.

Java8 was released by Oracle in 2014 and is the most revolutionary release since Java5.

Java8 absorbs the essence of other languages and brings functional programming, lambda expressions, streams, and a host of new features that will allow you to code efficiently and elegantically.

1. Lambda expression test

Lambada expressions can be understood as a concise expression of transitive anonymous functions. Lambda expressions have no name and have argument lists, function bodies, return types, and so on, just like normal methods.

A new thread prints a string. Lambda expressions are very succinct:

new Thread(() -> System.out.println("hello java8 lambda")).start()
Copy the code

The Thread class takes an instance of the Runnable type. A look at the Jdk source code shows that the Runnable interface is a functional interface that can be directly replaced by lambda expressions.

@FunctionalInterface
public interface Runnable {
    public abstract void run(a);
}
Copy the code

Lambda expression syntax is very simple:

() -> System.out.println("hello java8 lambda")
Copy the code
  • If there is only one parameter, you can write it as:a -> System.out.println(a)
  • -> arrows are fixed;
  • System.out.println("hello java8 lambda") Is the function body, if there are multiple statements to be wrapped in curly braces, such as the following:
(a, b) -> {int sum = a + b; returnsum; }Copy the code

To sum up, the Lambda expression module can be solidified as:

(parameter) -> {expression} 或者 (parameter) -> {statements; statements; }
Copy the code

Only one argument can omit parentheses

Using anonymous inner classes instead of Lambda expressions is less elegant.

// before Java8
new Thread(new Runnable() {
    @Override
    public void run(a) {
        System.out.println("hello java8 without lambda");
    }
}).start();
Copy the code

2. Lambda advanced usage

(1) Functional interface

A functional interface is one that defines only an abstract method. Note that Java8 allows default methods. Even if there are many default methods, as long as there is only one abstract method, the interface is still functional.

Functional interfaces usually have an annotation @functionalInterface on the class, such as:

@FunctionalInterface
public interface Runnable {
    public abstract void run(a);
}
Copy the code

(2) What can a functional interface do?

Lambda expressions are often used in conjunction with functional interfaces, providing implementations of abstract methods of functional interfaces in inline form, using the entire expression as an instance of the functional interface.

In the absence of lambda expressions, we typically use anonymous inner classes, as illustrated in the example code in section 1.

(3) Function descriptor

The signature of a functional interface abstraction method is basically the signature of a lambda expression, and we can call this correspondence a function descriptor. The process of abstracting from the abstract methods of a functional interface into a function descriptor is so important that knowing the function descriptor makes it easy to write lambda expressions. Here’s an example:

The Runnable interface has an abstract method void run() that takes an empty argument and returns void, so the function descriptor can be inferred as: () -> void

Lambda expressions can be written as () -> system.out.println (“hello java8 lambda”)

(4) Common functional interface

Java 8 uses functional interfaces. IntPredicate and LongPredicate are also defined for basic Java types. For details, see JDK source code.

Functional interface Function descriptor
Predicate T->boolean
Consumer T->void
Function<T,R> T->R
Supplier () -> T
UnaryOperator T -> T
BinaryOperator (T,T)->T
BiPredicate<L,R> (L,R)->boolean
BiConsumer<T,U> (T,U)->void
BiFunction<T,U,R> (T,U)->R

As for Predicate, Consumer, and Function, I’ll cover them in more detail in a later article, but just get a general idea.

(5) Refactor lambda expressions into method references

A method reference can be thought of as a shorthand for a lambda expression that can call a property’s methods and pass them as arguments. You can also think of method references as syntactic sugar for lambda expressions, making lambda expressions more concise to write. For example, in order of student age:

// before
students.sort((s1, s2) -> s1.getAge.compareTo(s2.getAge()))));
// after uses method references
students.sort(Comparator.comparing(Student::getAge()))));
Copy the code

There are three main types of method references:

  • Method references to static methods

ValueOf is a static method of the String class. The method reference is written as String::valueOf, which corresponds to the lambda expression: a -> string.valueof (a).

  • A method reference to an instance method of any type

Length is an instance method of the String class. The method reference is written as String::length, which corresponds to the lambda expression: (STR) -> str.length()

  • Method reference to an instance method of an existing object

The third is easily confused with the second, where an existing object refers to an instance method that calls an external object (not an input object) in a lambda expression, such as:

String str = "hello java8";
() -> str.length();
Copy the code

The corresponding method reference is written as STR ::length, not String::length

conclusion

Finally, three methods are quoted and summarized as follows:

Lambda expressions Method references
(args) -> ClassName.staticMethod(args) ClassName::staticMethod Static method method references
(arg0, params) -> arg0.instanceMethod(params) ClassName::instanceMethod Internal instance method references
arg0

(params) -> arg0.instanceMethod(params)
arg0.instanceMethod External instance method references

— END —

Daily praise: Hello technical people, praise first look to form a habit, your praise is my power on the way forward, the next stage is more exciting.

The blogger graduated from Huazhong University of Science and Technology with a master’s degree. He is a programmer who pursues technology and has passion for life. A few years in a number of first-line Internet companies, with years of actual combat experience.

Search the official wechat account “Architect who loves to laugh”, I have technology and story, waiting for you.

The articles are constantly updated, you can see my archived series of articles on Github /JavaMap, have interview experience and technical expertise, welcome Star.