Lambda Expression Beginner's Notes

Beginning experience with Lambda expressions

Creating threads by anonymous internal classes

//Improvement with anonymous internal classes
public class LambdaDemo {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Multithreaded program started");
            }
        }).start();
    }
}

Create threads by lambda expression

The way lambda expressions are used is more concise, as follows.

public class LambdaDemo {
    public static void main(String[] args) {
        new Thread(()->{
            System.out.println("Thread started");
        }).start();
    }
}

A Preliminary Study of lambda Expression

The three elements of a lambda expression

  • Formal parameters
  • Arrow
  • code block

Format of lambda expression

(Formal Parameter) -> (Code Block)

  • Formal parameters are separated by commas if there are more than one parameter, or if there are no blanks
  • -> is a fixed writing, representing a pointing action.
  • Code blocks are specific things to do, which are the contents of the method body we wrote earlier.

Prerequisites for using lambda expressions

1. There is an interface

2. There is only one abstract method in the interface

Exercise 1

  • Define an interface Eatable that defines an abstract method, void eat()
  • Define a test class (EatableDemo) that provides two methods in the test class.
    One method is useEatable
    One method is the primary method, which calls the useEatble() method.

Method 1

public class EatableDemo {
    public static void main(String[] args) {
        Eatable e=new EatableImpl();
        useEatable(e);
    }

    private static void useEatable(Eatable e){
        e.eat();
    }
}
public class EatableImpl implements Eatable{
    @Override
    public void eat() {
        System.out.println("One Day java,sql Don't touch it");
    }
}

public interface Eatable {
    void eat();
}

Method 2

public class EatableDemo {
    public static void main(String[] args) {
        useEatable(new EatableImpl(){
            @Override
            public void eat() {
                System.out.println("Today's School java,Transfer to R&D tomorrow");
            }
        });
    }

    private static void useEatable(Eatable e){
        e.eat();
    }
}
public class EatableImpl implements Eatable{
    @Override
    public void eat() {
        System.out.println("One Day java,sql Don't touch it");
    }
}
public interface Eatable {
    void eat();
}

Method 3

public class EatableDemo {
    public static void main(String[] args) {
        useEatable(()->{
            System.out.println("Pain in execution, tired in execution, two lines of tears in payroll");
        });
    }

    private static void useEatable(Eatable e){
        e.eat();
    }
}
public class EatableImpl implements Eatable{
    @Override
    public void eat() {
        System.out.println("One Day java,sql Don't touch it");
    }
}
public interface Eatable {
    void eat();
}

As you can see above, lambda expressions are indeed concise.

Exercise 2

  • Define an interface, Flyable, that defines an abstract method: void fly(String s)
  • Define a test class, FlyableDemo(Flyable f), that provides two methods in the test class
    One is useFlyable(Flyable f)
    The other is the main method, which calls useFlyable

Method 1

public class FlyableDemo {
    public static void main(String[] args) {
        useFlyable(new Flyable() {
            @Override
            public void fly(String s) {
                System.out.println(s);
                System.out.println("Sao Nian let's learn");
            }
        });

    }

    private static void useFlyable(Flyable f){
        f.fly("You still have to work overtime to write sql Are you?");
    }
}
public interface Flyable {
    void fly(String s);
}

Method 2

public class FlyableDemo {
    public static void main(String[] args) {
        useFlyable((String s)->{
            System.out.println(s);
            System.out.println("Quick Learning java,Three years to refine");
        });

    }

    private static void useFlyable(Flyable f){
        f.fly("You still have to work overtime to write sql Are you?");
    }
}
public interface Flyable {
    void fly(String s);
}

Exercise 3

public class AddableDemo {
    public static void main(String[] args) {
        useAddable((int x,int y)->{
            return x+y;
        });

    }

    private static void useAddable(Addable a){
        int sum=a.add(10,20);
        System.out.println(sum);
    }
}
public interface Addable {
    int add(int x,int y);
}

Omitting patterns of lambda expressions

The type of the parameter can be omitted (you cannot omit only one if you have more than one parameter)

For example, you can remove the parameter type of a lambda expression

public class AddableDemo {
    public static void main(String[] args) {
        useAddable((x,y)->{
            return x+y;
        });

    }

    private static void useAddable(Addable a){
        int sum=a.add(10,20);
        System.out.println(sum);
    }
}


If there is only one parameter, parentheses can be omitted

public class AddableDemo {
    public static void main(String[] args) {
        useFlyable(s->{
            System.out.println(s);
        });

    }

    private static void useFlyable(Flyable f){
        f.fly("Beautiful boy is me, please give me some compliment");
    }
}
public interface Flyable {
    void fly(String s);
}

If a statement in a code block has only one sentence, braces and semicolons can be omitted

public class AddableDemo {
    public static void main(String[] args) {
        useFlyable(s->
            System.out.println(s)
        );

    }

    private static void useFlyable(Flyable f){
        f.fly("Beautiful boy is me, please give me some compliment");
    }
}
public interface Flyable {
    void fly(String s);
}

If the statement in the code block has only one sentence, either braces and semicolons or return can be omitted

public class AddableDemo {
    public static void main(String[] args) {
        useAddable((x,y)-> x+y);

    }
    private static void useAddable(Addable a){
        int sum=a.add(10,20);
        System.out.println(sum);
    }
}
public interface Flyable {
    void fly(String s);
}

Notes on lambda expressions

  • lambda expressions must have an interface and require that there be only one abstract method in the interface
  • A context is required to deduce the lambda interface
 public class AddableDemo {
   public static void main(String[] args) {
       Runnable r = () -> {
           System.out.println("nice to meet you");
       };
       new Thread(r).start();
   }
}

In the example above, the context is provided to the left of the equal sign to derive the type of lambda expression. This is based on the assignment of local variables.

It can also be obtained by calling the parameters of the method.

public class AddableDemo {
    public static void main(String[] args) {

        new Thread(()-> System.out.println("hello")).start();
    }
}

Differences between lambda expressions and anonymous inner classes

Tags: Java

Posted on Wed, 22 Sep 2021 13:48:37 -0400 by webdevelope