Java8 - Lambda表达式

167 阅读2分钟

函数式编程

  • 在维基百科上,函数式编程的定义如下:“函数式编程是一种编程范式。它把计算当成是数学函数的求值,从而避免改变状态和使用可变数据。它是一种声明式的编程范式,通过表达式和声明而不是语句来编程。” 因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数我们称之为没有副作用。
  • 函数式编程(Functional Programming)是把函数作为基本运算单元,函数可以作为变量,可以接收函数,还可以返回函数。历史上研究函数式编程的理论是Lambda演算,所以我们经常把支持函数式编程的编码风格称为Lambda表达式。
  • 通过表达式来替换匿名类函数编写。

关于函数式编程推荐阅读以下文章:

书写形式

() -> {}
arg1 -> {}
(arg1, arg2) -> {}

双冒号

T::func
T::new

内部函数 -> Lambda

Demo1

Thread thread =new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("start Runnable");
    }
});
thread.start();

使用Lambda, Runnable接口为无参数返回空。推到为 () -> {}

Thread thread =new Thread(() -> System.out.println("start Runnable"));
thread.start();

Demo2

定义接口 传入为 T 返回 为 R

@FunctionalInterface
public interface Function<T, R> {
    // 对类型为T的对象执行操作,返回 R
    R apply(T t);
}

定义实体类 People

@Data
public class People {
    private String name;
    private Integer age;
}

实现Function,传入People,获取People中的name属性。

Function<People,String> function = new Function<People, String>() {
    @Override
    public String apply(People people) {
        return people.getName();
    }
};

利用Function获取People的name

People people = new People();
people.setName("A001");
people.setAge(20);

String name = function.apply(people);

使用lambda后实现Function接口。

Function<People,String> function = people1 -> people1.getName();

Function<People,String> function = People::getName;

Java 8 中 提供的 FunctionalInterface

Java 8 增加了函数式编程的支持,所以又增加了一类定义,即所谓FunctionalInterface,简单说就是只有一个抽象方法的接口,通常建议使用@FunctionalInterface 注解进行标记。

例,Java 8 中提供的一套FunctionalInterface 接口。

@FunctionalInterface
public interface Function<T, R> {
    // 对类型为T的对象执行操作,返回R
    R apply(T t);
}

消费类型

@FunctionalInterface
public interface Consumer<T> {
    // 对类型为T的对象执行操作,返回为空
    void accept(T t);    
}

提供类型

@FunctionalInterface
public interface Supplier<T> {
    // 返回T
    T get();
}

断言类型

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}