[Lambda] Java Functional Programming

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/meiqi0538/article/details/102766272

Acquaintance lambda expression

Using functional programming ideas. In mathematics, the function is input, to output a calculated amount of a program, which is the data operation. For Java, it takes the object-oriented thinking, stressing that "something must be done in the form of an object." Functional thought is try to ignore the complexity of object-oriented syntax: "emphasize what to do, rather than what form do."
Now we use a case to experience Lambda Expressions:
Demand: start a thread in the console output sentence: "multithreaded program started" (here need to understand the relevant knowledge thread)
Mode 1:

  • Define a class MyRunnable implement Runnable, override run () method
package com.pqd.lambda;

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("多线程程序启动了");
    }
}
  • MyRunnable create an object class (in the main method)
  • Thread Startup object class, the object MyRunnable configured as transmission parameters
  • Start a thread
package com.pqd.lambda;
/*
需求:启动一个线程,在控制台输出一句话:“多线程程序启动了”
 */
public class LambdaDemo {
    public static void main(String[] args) {
        MyRunnable my = new MyRunnable();
        Thread t = new Thread(my);
        t.start();
    }
}

Run the program are:

can see in order to accomplish a relatively small feature, we need to write a new class, and want to create a class that implements the master class and the Thread object to accomplish this is too much trouble.

To simplify the code written, we used 2, Method a way anonymous inner classes, as follows:

package com.pqd.lambda;
/*
需求:启动一个线程,在控制台输出一句话:“多线程程序启动了”
 */
public class LambdaDemo {
    public static void main(String[] args) {
        // 实现类的方式显示需求
        MyRunnable my = new MyRunnable();
        Thread t = new Thread(my);
        t.start();
        // 匿名内部类的方式改进
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("多线程程序启动了");
            }
        }).start();
    }
}


By contrast, this approach does not create a class, relatively simple thing, but this format is more complex, then there is an easier way than this thing? Of course, that is our third approach Lambda expressions, as follows:

As can be seen Lambda is very simple, it only focus on what the situation, no complicated format, does not need to take the definition of a class.

Lambda expressions standard format

根据上面的案例,我们对比方式二和方式三有,匿名内部类中重写run()方法涉及到:

  • 方法形式参数为空,说明调用方法时不需要传递参数
  • 方法返回类型为void,说明方法执行没有结果返回
  • 方法体中的内容,是我们具体要做的事情

而Lambda表达式的代码有:

  • ():里面没有内容,可以看成时方法形式参数为空
  • ->:用箭头指向后面要做的事情
  • {}:包含一段代码,我们称之为代码块,可以看成是方法体中的内容

那么也就很好了解Lambda表达式的标准格式了

  • 格式:(形式参数)->{代码块}
  • 形式参数:如果有多个参数,参数之间用逗号隔开,如果没有参数,留空即可
  • ->:由英文中画线和大于符号组成,固定写法,代表指向动作
  • 代码块:是我们具体要做的事情,也就是以前我们写的方法体中的内容

几个案例巩固一下

需要了解的是:Lambda表达式的使用前提是有一个接口接口中有且仅有一个抽象方法

练习1 无参数情况(使用实现类的方式、匿名内部类、Lambda表达式做对比)

  • 定义一个接口(Eatable),里面定义一个抽象方法,void eat();
package com.pqd.lambda;

public interface Eatable {
    void eat();
}
  • 定义一个测试类(EatableDemo),在测试类中提供两个方法:useEatable(Eatable e),一个是主方法,在主方法中调用useEatable方法,这里我们也许去实现这个接口的抽象函数。
package com.pqd.lambda;

public class EatableImpl implements Eatable{
    @Override
    public void eat() {
        System.out.println("一天一苹果,医生远离我");
    }
}

现在我们在测试类中进行书写

package com.pqd.lambda;

public class EatableDemo {
    public static void main(String[] args) {
        // 在主方法中调用useEatable方法
        // 实现类的方式
        EatableImpl e = new EatableImpl();  // 多态
        useEatable(e);
    }
    private static void useEatable(Eatable e){
        e.eat();
    }
}

上面是实现类的方式进行实现的,现在我们使用匿名内部类的方式来书写,如下:

useEatable(new Eatable() {
            @Override
            public void eat() {
                System.out.println("一天一苹果,医生远离我");
            }
        });

最后我们使用Lambda表达式来书写:

useEatable(() ->{
            System.out.println("一天一苹果,医生远离我");
        });

练习2(有参无返回值)

  • 定义一个接口(Flyable),里面定义一个抽象方法:void fly(String s);
package com.pqd.lambda;

public interface Flyable {
    void fly(String s);
}
  • 定义一个测试类(FlyableDemo),在测试类中提供两个方法:useFlyable(Flyable f),主方法,在主方法中调用useFlyable方法
package com.pqd.lambda;

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("飞机自驾游");
            }
        });
    }
    public static void useFlyable(Flyable f){
        f.fly("风和日丽,晴空万里");
    }
}

下面使用Lambda表示来书写

// Lambda表达式
        useFlyable((String s) ->{
            System.out.println(s); // 传入的参数
            // 自己的内容
            System.out.println("飞机自驾游");
        });

练习3(有参有返回值)

  • 定义一个接口(Addable),里面定义一个方法:int add(int x, int y);
package com.pqd.lambda;

public interface Addable {
    int add(int x, int y);
}
  • 定义一个测试类(AddableDemo),在测试中提供两个方法:一个方法是useAddable(Addable a),主方法调用useAddable方法
package com.pqd.lambda;
public class AddableDemo {
    public static void main(String[] args) {
        // 直接使用Lambda表达式
        useAddable((int x, int y) ->{
            return  x + y; // 对add()具体的实现
        });
    }
    private static void useAddable(Addable a){
        int add = a.add(10, 20);
        System.out.println(add);
    }
}

Lambda表达式的省略模式

  • 参数类型可以省略,但是有多个参数的情况下,不能只能略一个参数的类型
  • 如果参数有且只有一个,那么小括号可以省略
  • 如果代码块的语句只有一条,可以省略大括号和分号,甚至是return

我们使用之前的例子来说明

package com.pqd.lambda;

public class LambdaDemo1 {
    public static void main(String[] args) {
        useAddable((int x, int y) -> {
            return x + y;
        });
        // 参数可以省略类型, 不能只省略一个
        useAddable(( x, y) -> {
            return x + y;
        });
        // 如果参数有且只有一个, 小括号也可省略
        useFlyable( s ->{
            System.out.println(s);
        });
        // 如果代码块语句只有一条,可以省略大括号和分号
        useFlyable( s -> System.out.println(s));

        // 如果有return 其也要省略(代码块只有一条语句)
        useAddable(( x, y) -> x + y);
    }
    private static void useFlyable(Flyable f){
        f.fly("风和日丽,晴空万里");
    }
    private static void useAddable(Addable a){
        int add = a.add(10, 20);
        System.out.println(add);
    }
}

注意事项

  • 使用Lambda必须要有接口,并且要求接口中有且只有一个抽象方法
  • 必须有上下文环境,才能推导Lambda对应的接口,
    • 根据局部变量赋值得知Lambda对应的接口:Runnable r = () -> System.out.println(“Lambda表达式”);
    • 根据调用方法的参数得知Lambda对应的接口:new Thread(()-> System.out.println(“Lambda表达式”)).start();

Lambda表达式于匿名内部类之间的区别

  • 所需类型不同:匿名内部类可以是:接口(可有多个方法),抽象类,具体类 ,Lambda表达式只能是接口
  • 使用限制不同:如果接口中多于一个抽象方法,只能使用匿名内部类,而不能使用Lambda表达式
  • 实现原理不同:编译之后,匿名内部类,产生一个单独的.class字节码文件,Lambda,没有一个单独的.class字节码文件。对应的字节码文件会在运行的时候动态生成。

个人订阅号
更多编程,人工智能知识等着你
image

Guess you like

Origin blog.csdn.net/meiqi0538/article/details/102766272