Introduction to Lambda expressions

One of the big highlights of Java 8 is the introduction of Lambda expressions, which make code designed with them much more concise. Lambda expressions can be used to implement interfaces instead of the anonymous inner classes we used to write. Lambda expressions are essentially anonymous functions;

Experience Lambda expressions

Let’s take a look at Lambda expressions with a small example; We define a compute interface with only one method add;

public class Program {

    public static void main(String[] args) {
        Cal c1=new Cal() {
            @Override
            public int add(int a, int b) {
                returna+b; }};int c=c1.add(1.2); System.out.println(c); }}interface Cal{
     int add(int a,int b);
}
Copy the code

This is our old implementation, anonymous inner class, and then call execution; Let’s rewrite this with a Lambda expression:

public class Program {

    public static void main(String[] args) {
        Cal c1=(int a,int b) ->{returna+b; };int c=c1.add(1.2);
        System.out.println(c);
    }

    int add(int a,int b){
        returna+b; }}interface Cal{
     int add(int a,int b);
}
Copy the code

Anonymous inner class, changed to:

Cal c1=(int a,int b) ->{returna+b; };Copy the code

It’s much simpler;

Feel like Lambda expressions are powerful,

Let’s look at the syntax of Lambda expressions;

Lambda expression syntax

Let’s look at the Lambda expression:

(int a,int b) ->{returna+b; };Copy the code

This is essentially a function; The general function is as follows:

int add(int a,int b){
  return a+b;
}
Copy the code

Lambda expression functions have only the argument list and the method body;

(Parameter list) -> {method body}

Description: () : used to describe a parameter list; {} : used to describe the method body; -> : Lambda operator, which can be called arrow symbol, or goes to

Lambda expression syntax is explained in detail

Let’s take an example, interface method parameters, no arguments, single argument, two arguments, return value, no return value, these six cases are listed:

interface If1{

    /** * No parameter no return value */
     void test(a);
}


interface If2{

    /** * No return value * for a single parameter@param a
     */
    void test(int a);
}

interface If3{

    /** * Two parameters have no return value *@param a
     * @param b
     */
    void test(int a,int b);
}


interface If4{

    /** * No argument has a return value *@return* /
    int test(a);
}

interface If5{

    /** * A single parameter has a return value *@param a
     * @return* /
    int test(int a);
}

interface If6{

    /** * Multiple arguments have return values *@param a
     * @param b
     * @return* /
    int test(int a,int b);
}
Copy the code

We use Lambda expressions to implement:

// No parameter no return value
If1 if1=()->{
  System.out.println("No argument, no return value");
};
if1.test();

// No return value for a single parameter
If2 if2=(int a)->{
  System.out.println("No return value for a single parameter a="+a);
};
if2.test(3);

// Two parameters have no return value
If3 if3=(int a,int b)->{
  System.out.println("No return value for two parameters a+b="+(a+b));
};
if3.test(2.3);

// No argument has a return value
If4 if4=()->{
  System.out.print("No arguments return value");
  return 100;
};
System.out.println(if4.test());


// A single parameter has a return value
If5 if5=(int a)->{
  System.out.print("Single parameter has return value");
  return a;
};
System.out.println(if5.test(200));

// Multiple parameters have return values
If6 if6=(int a,int b)->{
  System.out.print("Multiple parameters have return values");
  return a+b;
};
System.out.println(if6.test(1.2));
Copy the code

Run output:

None Parameter None Returned value A = for a single parameter3Two parameters have no return value a+b=5No parameter has a return value100Individual arguments have return values200Multiple parameters have return values3
Copy the code

Lambda expression compact syntax

Concise syntax:

  • Parameter types can be omitted
  • If there is only one argument, the () parentheses can be omitted
  • If the method body has only one statement, the {} braces can be omitted
  • If the only statement in the method body is a return statement, the return that omits braces is also omitted

Rewriting examples:

/ * * *@authorJava1234_ small feng *@site www.java1234.com
 * @companyJava Knowledge Sharing network *@createThe 2020-08-12 departed * /
public class Program2 {

    public static void main(String[] args) {
        // 1, the parameter type can be omitted
        // 2, if there is only one argument, the () parentheses can be omitted
        If the method body has only one statement, the {} braces can be omitted
        If the only statement in the method body is a return statement, omit braces for return

        // No parameter no return value
        If1 if1=()->System.out.println("No argument, no return value");
        if1.test();

        // No return value for a single parameter
        If2 if2=a->System.out.println("No return value for a single parameter a="+a);
        if2.test(3);

        // Two parameters have no return value
        If3 if3=(a,b)->{
            System.out.println("No return value for two parameters a+b="+(a+b));
        };
        if3.test(2.3);

        // No argument has a return value
        If4 if4=()->100;
        System.out.println(if4.test());


        // A single parameter has a return value
        If5 if5=a->{
            System.out.print("Single parameter has return value");
            return a;
        };
        System.out.println(if5.test(200));

        // Multiple parameters with return values parameter types can be omitted
        If6 if6=(a,b)->a+b;
        System.out.println(if6.test(1.2)); }}Copy the code

Method references

Sometimes when multiple lambda expression implementation functions are the same, we can encapsulate them into generic methods for easier maintenance. Static method :: method: static method :: method: static method :: method

Examples are as follows:

public class Program2 {

    public static void main(String[] args) {
        // Method reference
        / / syntax:
        // static method name :: method name
        // Common method object name :: method name
        Program2 program2=new Program2();
        If5 if5=program2::test;
        If5 if52=Program2::test2;
        System.out.println(if5.test(1));
        System.out.println(if52.test(1));


    }

    public int test(int a){
        return a-2;
    }

    public static int test2(int a){
        return a-2; }}Copy the code

Constructor reference

Constructor references can be used if the implementation of a functional interface happens to be implemented by calling a class constructor. Syntax: Class name ::new

Example: Define a Dog entity to implement both no-parameter and parameter-constructor;

public class Dog {

    private String name;

    private int age;

    public Dog(a) {
        System.out.println("Parameterless construction method");
    }

    public Dog(String name, int age) {
        System.out.println("Parametric construction method");
        this.name = name;
        this.age = age;
    }


    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge(a) {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString(a) {
        return "Dog{" +
                "name='" + name + '\' ' +
                ", age=" + age +
                '} '; }}Copy the code

In defining two interfaces:

interface DogService{
    Dog getDog(a);

}

interface DogService2{
    Dog getDog(String name,int age);
}
Copy the code

Testing:

public class Program3 {

    public static void main(String[] args) {

        // Common mode
        DogService dogService=()->{
            return new Dog();
        };
        dogService.getDog();

        // Simplify
        DogService dogService2=()->new Dog();
        dogService2.getDog();

        Constructor reference
        DogService dogService3=Dog::new;
        dogService3.getDog();

        // Constructor references have arguments
        DogService2 dogService21=Dog::new;
        dogService21.getDog("Millet".11); }}Copy the code

Execution Result:

Nonparametric construction method Nonparametric construction method Parametric construction methodCopy the code

Comprehensive instance

Let’s take a closer look at lambda expression usage through a comprehensive example of a lambda operation set.

public class Program4 {

    public static void main(String[] args) {
        List<Dog> list=new ArrayList<>();
        list.add(new Dog("aa".1));
        list.add(new Dog("bb".4));
        list.add(new Dog("cc".3));
        list.add(new Dog("dd".2));
        list.add(new Dog("ee".5));
        / / sorting
        System.out.println("Lambda set sort");
        list.sort((o1,o2)->o1.getAge()-o2.getAge());
        System.out.println(list);

        // iterate over the collection
        System.out.println(Lambda ergodic set); list.forEach(System.out::println); }}Copy the code

Run output:

Lambda sets sort [Dog{name='aa', age=1}, Dog{name='dd', age=2}, Dog{name='cc', age=3}, Dog{name='bb', age=4}, Dog{name='ee', age=5}] lambda traversal collection Dog{name='aa', age=1}
Dog{name='dd', age=2}
Dog{name='cc', age=3}
Dog{name='bb', age=4}
Dog{name='ee', age=5}
Copy the code

Let’s look at the sort method of the set,

The sort method has a Comparator interface.

We can easily do this with lambda:

(o1,o2)->o1.getAge()-o2.getAge()
Copy the code

Let’s look at the forEach method for the set, and click in:

There is a Consumer interface, click on it again:



The interface has an accept method for interface parameters.

So we directly refer to the method directly output each traversal value can be;

System.out::println

@ FunctionalInterface annotations

We saw that the Consumer interface, the Comparator interface had @functionalInterface;

This annotation is a functional interface annotation. A functional interface is, of course, an interface, and then there can only be one abstract method in that interface. This type of interface is also known as the SAM interface, or Single Abstract Method interfaces

The characteristics of

  • Interfaces have one and only one abstract method
  • Allows static methods to be defined
  • Allows default methods to be defined
  • Allows public methods in java.lang.object

This annotation is not required, and it does not matter if an interface meets the definition of a “functional interface”. Adding this annotation makes it easier for the compiler to check. If you write @functionInterface instead of a functional interface, the compiler will report an error

The instance

// The correct functional interface
@FunctionalInterface
public interface TestInterface {
 
    // Abstract methods
    public void sub(a);
 
    // Public method in java.lang.object
    public boolean equals(Object var1);
 
    // The default method
    public default void defaultMethod(a){}// Static method
    public static void staticMethod(a){}}// Wrong functional interface (multiple abstract methods)
@FunctionalInterface
public interface TestInterface2 {

    void add(a);
    
    void sub(a);
}
Copy the code

System built-in functional interface

The introduction of Java8, Lambda important features, together with the introduction of the system built in a series of functional interfaces;

The java.util.function package of the JDK provides a set of built-in functional interfaces:



Consumer, Comparator, Predicate, Supplier, etc.

Lambda expressions video tutorial

Thank you for your attention. Brother Feng has specially recorded a video tutorial for you to have a deeper grasp of the principle and application of Lambda. Mainly with IDEA development tools, to explain lambda expressions, hope friends quickly master.

The paper come zhongjue shallow, and must know this to practice.

Need more practice, more thinking

B standing video tutorial online address: https://www.bilibili.com/video/bv1ci4y1g7qD

About feng brother

[author] : Feng Ge [wechat] : Java9568 (add friends, please note CSDN) [public number] : Java1234. Welcome everyone to pay attention to ~ 【 author introduction 】 : Jiangsu Normal University computer department, Java senior old driver, has been the State Grid power, many small companies at the front line of the code; At present, I have started a studio in Nantong, my hometown. I have settled the house, car, wife and children. Hope to become friends with all readers; Discuss Java technology and Java entrepreneurship together;