Java8之lambda表达式

简述

Java8发布了很多的新特性,其中lambda表达式是一个重要的部分
(虽然Java11已经发布了 ⊙▽⊙)

1、先来看一个新建线程的例子

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(666);
            }
        });

在Thread的构造函数中传入Runnable实例,由于Runnable是一个接口,所以需要实现其中的抽象方法run

2、改为lambda表达式后

Thread t1 = new Thread(() -> System.out.println(666));

嘿嘿嘿,是不是异常简洁呢?
通过感性的对比,我们大致可以发现,()代表run方法名, 箭头和后面的语句表示定义整个方法体。这里我们会有疑问,转换为简洁的lambda表达式需要什么约束呢?下面我们开始介绍!

函数式接口

  • 只有函数式接口,才可以转换为lambda表达式,什么是函数式接口呢?
  • 有且只有一个抽象方法的接口被成为函数式接口!
  • 函数式接口可以显式的被@FunctionalInterface所表示,当被标识的接口不满足规定时,编译器会提示报错

Runnable接口就是一个函数式接口

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

转换方式

1、当函数式接口内的唯一抽象方法没有参数时,可以使用如下方式

//如果方法体内只有一条语句
//无返回值
() -> System.out.println("test");
//有返回值,不需要显示的return
() -> new Student();

//如果有多条语句,需要用{}包围
//无返回值
() -> {
    int a = 1;
    int b = 2;
    System.out.println(a * b);
};
//有返回值
() -> {
    int a = 1;
    int b = 2;
    return a * b;
};

2、当函数式接口内的唯一抽象方法含有参数时,写法与上面基本相同,只是需要把对应参数写到()里面

//不需要指明参数类型,会根据实际方法中的类型自动推测
//只有一个参数可以省略括号
(arg1, arg2, arg3) -> System.out.println(arg1 * arg2 * arg3);

3、举个例子

//自定义一个函数式接口
@FunctionalInterface
public interface MyInterface {
    void method(int a, int b);
}
    //使用lambda表达式
    public static void main(String[] args) {
        MyInterface myInterface = (a, b) -> System.out.println(a + b);
        myInterface.method(1, 2);//3
    }

意义

首先毋庸置疑,lambda表达式十分简洁。
其次,在传统的java面向对象编程中,我们在方法内只可以传递值或对象引用,无法传递方法。
当我们想要在方法中传递方法,或者说是传递行为的时候,如Java Swing或者Android开发中,经常需要我们实现监听接口中的方法,这就是一种行为的传递。

private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
             //代码省略
        }
 };

这种行为的传递需要依赖接口实现类实例,但是我们只关心方法内部的逻辑实现,所以使用lambda表达式可以实现这一目标

private Handler handler = msg -> {
    //代码省略
};
//但实际上lambda并没有脱离接口,仍然依附于接口实现类实例

Java8内置的函数式接口

Java8提供了一个java.util.function包,包含了很多函数式接口,我们来介绍最为基本的4个(为了节省篇幅,去掉了源码中的注释)

Function接口
@FunctionalInterface
public interface Function {

    R apply(T t);

    default  Function compose(Function before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    default  Function andThen(Function after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    static  Function identity() {
        return t -> t;
    }
}

Function接口的唯一抽象方法是apply,作用是接收一个指定类型的参数,返回一个指定类型的结果

import java.util.function.Function;
public class FunctionTest {
    public static void main(String[] args) {
        FunctionTest ft = new FunctionTest();
        //使用lambda表达式实现apply方法,返回入参+10。形式上如同传递了一个方法作为参数
        int res = ft.compute(1, v -> v + 10);
        System.out.println(res);//11
    }

    public int compute(int a, Function function){
        //使用者在使用本方法时,需要去编写自己的apply,
        //传递的funtion是一个行为方法,而不是一个值
        return function.apply(a);
    }

默认方法compose作用是传入参数后,首先执行compose方法内的Function的apply方法,然后将其返回值作为本Function方法的入参,调用apply后得到最后返回值

import java.util.function.Function;
public class FunctionTest {
    public static void main(String[] args) {
        FunctionTest ft = new FunctionTest();
        //调用compose
        //先+8,然后将得到的值*3
        System.out.println(ft.compute(2, v -> v * 3, v -> v + 8));//30
    }
    public int compute(int a, Function function1, Function function2){
        //将function2先接收入参a,调用apply后,将返回值作为新的入参,传入function1,调用apply返回最后结果
        return function1.compose(function2).apply(a);
    }

默认方法andThen与compose正好相反,先执行本Function的apply,然后将结果作为andThen方法参数内的Function的入参,调用apply后返回最后结果

import java.util.function.Function;
public class FunctionTest {
    public static void main(String[] args) {
        FunctionTest ft = new FunctionTest();
        //调用andThen
        //先*3,然后将得到的值+8
        System.out.println(ft.compute(2, v -> v * 3, v -> v + 8));//14
    }
    public int compute(int a, Function function1, Function function2){
        //将function2先接收入参a,调用apply后,将返回值作为新的入参,传入function1,调用apply返回最后结果
        return function1.andThen(function2).apply(a);
    }

静态方法identity的作用是传入啥返回啥,这里就不写例子了

Consumer接口
package java.util.function;

import java.util.Objects;
@FunctionalInterface
public interface Consumer {

    void accept(T t);

    default Consumer andThen(Consumer after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

Consumer接口中accept方法的作用是接收指定参数类型,无返回值,重点在于内部消费

Consumer consumer = s -> System.out.println("hello " + s);
consumer.accept("mike");// hello mike

默认方法andThen作用是连续消费,从本Consumer开始,从外到内,针对同一入参。

Consumer consumer = s -> System.out.println("hello " + s);
Consumer consumer2 = s -> System.out.println("nice to meet you " + s);
consumer.andThen(consumer2).accept("mike");
//hello mike
//nice to meet you mike
Predicate接口
package java.util.function;

import java.util.Objects;
@FunctionalInterface
public interface Predicate {

    boolean test(T t);

    default Predicate and(Predicate other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    default Predicate negate() {
        return (t) -> !test(t);
    }

    default Predicate or(Predicate other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    static  Predicate isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

Predicate中的test方法,传入指定类型参数,返回布尔类型的结果,用于判断,断言

//判断一个数是否是偶数
Predicate predicate = b -> n % 2 == 0;
System.out.println(predicate.test(3));
//false

默认方法and顾名思义,将本Predicate和and参数中的Predicate对同一入参进行test的结果进行【与】操作。
negate方法对test的结果进行【非】操作
or方法对两个Predicate的test结果进行【或】操作

静态方法isEqual将其入参与test方法的入参进行equals比较

System.out.println(Predicate.isEqual(1).test(1));//true
Supplier接口
package java.util.function;
@FunctionalInterface
public interface Supplier {
    T get();
}

Supplier意为供应,只有一个方法get,不接收任何参数,只返回指定类型结果

Supplier sup = () -> "hello world";
System.out.println(sup.get());
总结

以上就是function包中最为基础的四个函数式接口,不管是接口名称还是方法名称,都是见名知意,十分形象。
当然funtion包下还有很多其他接口,但基本都与这四个接口有关。如BiFunction是接收两个参数,DoubleConsumer是强制接收double类型的参数,更多函数式接口点进去源码一看注释便知道如何使用!

你可能感兴趣的:(Java8之lambda表达式)