JDK8 Lambda expression introduction

  1. Understand the Open JDK and Oracle JDK
  2. JDK8 new features
  • Lambda new features
  • The Stream operation of the collection
  • Interface enhancement
  • Parallel array sort
  • Optional avoids Null checking
  • New time and date API
  • Repeatable annotation
  1. This section describes the official website of the OpenJdk

Problems with using anonymous inner classes

When a Thread needs to be started to complete a task, the task content is usually defined through the Runable interface or the Thread class is used to start the Thread.

The traditional way of writing it is as follows
 public static void main(String[] args) {
      
        new Thread(new Runnable() {
            @Override
            public void run(a) {
                System.out.println("New thread executing code.");
            }
        }).start();
    }
Copy the code

Because of object-oriented syntax, it is preferred to create an anonymous class object of the Runable interface that specifies the content of the task to be performed by the thread, and then hand it off to a thread to start.

The code analysis

There are a few things you can analyze about Runable’s use of anonymous inner classes:

  • The Thread class takes the Runable interface as a parameter, where the abstract run() is used to specify the core of the Thread’s task content
  • To specify the method body of run(), you have to need the implementation class of the Runable interface
  • To save you the trouble of defining a Runable implementation class, you have to use anonymous inner classes
  • The abstract run method must be overridden, so the method name, method parameters, and method return values must be written again without error
  • In fact, only the method body seems to be the key

Lambda experience

Lambda is an anonymous function that can be understood as a piece of code that can be passed

Lambda expression is written as follows

Thanks to java8’s new syntax, the above anonymous inner class writing of the Runable interface can achieve the same effect with simpler lambda expressions

 public static void main(String[] args) {
        new Thread(()->{
            System.out.println("New thread executing code.");
        }).start();
 }
Copy the code

This code is exactly the same as before and can be passed at the compile level of JDK8 or higher. As you can see from the semantics of the code, we start a thread, and the contents of the thread task are specified in a more concise form. We just need to zoom the code we’re about to execute into a lambda expression, no classes need to be defined, no objects need to be created.

We can understand Lambda as a rewrite of an interface’s abstract method

The advantages of lambda

Simplify the use of anonymous inner classes and make the syntax more concise

Lambda leaves out the object-oriented rules, and the standard Lambda expression format consists of three parts:

(Parameter type Parameter name) -> {code body}Copy the code

Format specification

  • (Parameter Type Parameter name): parameter list
  • {code body}: method body
  • ->: arrow that separates parameters and method bodies

Lambda versus method

Anonymous inner class

 public void run(a) {
    System.out.println("New thread executing code.");
 }
Copy the code

Lambda expressions

() ->{  System.out.println(Lambda executes code); }
Copy the code

Lambda with no arguments and no return value

Having mastered the syntax of Lambda, let’s get familiar with the use of Lambda through a case study

public interface Swimmable {
    public abstract  void swimming();
}
Copy the code
public class demo01LambdaUse {
    public static void main(String[] args) {
        goSwimming(new Swimmable() {
            @Override
            public void swimming(a) {
                System.out.println("I'm swimming in the anonymous inner class"); }}); goSwimming( (()->{ System.out.println("I am the swim of Lambda.");
        }));
    }

  

    Lambda expression with no return value for the argument
    private static void goSwimming(Swimmable swimmable) { swimmable.swimming(); }}Copy the code

Lambda that has an argument with a return value

The following example illustrates the usage scenario code for the java.util.Comparator

interface, where the abstract method is defined as:

  • public abstract int compare(T o1, T o2)

When sorting a collection of objects, collections.sort () requires an instance of the Comparator interface to specify the rules for sorting

The traditional writing

public class Person {
    private  String name;
    private int age;
    private doubleheight; . Omit some code}Copy the code
package com.example.jdk.demo01Lamdba;

import java.util.*;

/ * * *@author meteor
 */
public class demo01LambdaParam {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Andy Lau".55.178.7));
        personList.add(new Person(Jacky Cheung.56.179.7));
        personList.add(new Person(Aaron Kwok.57.177.7));
        personList.add(new Person("Dawn".58.176.7));

        Collections.sort(personList, new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                returno1.getAge() - o2.getAge(); }});for(Person person : personList) { System.out.println(person); }}}Copy the code

Lambda method

package com.example.jdk.demo01Lamdba;

import java.util.*;

/ * * *@author meteor
 */
public class demo01LambdaParam {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Andy Lau".55.178.7));
        personList.add(new Person(Jacky Cheung.56.179.7));
        personList.add(new Person(Aaron Kwok.57.177.7));
        personList.add(new Person("Dawn".58.176.7));

        Collections.sort(personList,(Person o1, Person o2)->{
            return o2.getAge() - o1.getAge();
        });
        
        for(Person person : personList) { System.out.println(person); }}}Copy the code