美文网首页Java学习笔记Java 杂谈
Java8 函数式接口 与 Lambda 及 方法引用

Java8 函数式接口 与 Lambda 及 方法引用

作者: 聪明的奇瑞 | 来源:发表于2018-02-10 11:56 被阅读186次

函数式接口

  • Lambda 表达式只能在函数式接口上操作,函数式接口是具有单个抽象方法的接口,也称为 SAM(Single Abstract Method)
  • 函数接口可以有任意的 default 或 static 方法

函数式接口例子

  • 最基本的函数式接口
public interface Foo1 {
    void bar();
}
public interface Foo1 {
    int bar(boolean bz);
}
public interface Foo1 {
    String bar(Object baz, int mink);
}
  • default 方法不会被计算到函数式接口的单个抽象方法里
public interface Foo1 {
    default String bar() {          
        return "baz";
    }
    void quux();
}
  • 可以使用 @FunctionalInterface 注解,该注解可以让编译器帮我们审核该接口是否函数式接口
@FunctionalInterface
public interface Foo1 {
    void bar();
}
@FunctionalInterface
interface BlankFoo1 extends Foo1 {       // 从Foo1继承抽象方法
}
@FunctionalInterface
interface Foo1 {
    void bar();
    boolean equals(Object obj);         // 重写 Object 的方法因此不计算
}
  • 下面不是一个函数式接口,因为它没有任何方法
@FunctionalInterface
interface Foo1 {}

Lambda 表达式

  • 任何函数的参数只要是一个函数式接口都能接收一个 Lambda
  • 案例准备:
public interface TestFunctionInterface1 {
    void print();
}
public interface TestFunctionInterface2 {
    void print(String name);
}
public interface TestFunctionInterface3 {
    void print(String name,int age);
}

// 与静态方法

public static void print(TestFunctionInterface1 testFunctionInterface) {
        testFunctionInterface.print();
    }

public static void print(TestFunctionInterface2 testFunctionInterface) {
        testFunctionInterface.print("linyuan");
    }

public static void print(TestFunctionInterface3 testFunctionInterface) {
        testFunctionInterface.print("linyuan", 21);
    }
  • 通过 Lambda(“闭包”或“匿名方法”)表达式
print(()->System.out.println("Hello"));

// 等同于 

print(new TestFunctionInterface(){
    @Override
    public void print(){
        System.out.println("Hello");
    }
});
  • Lambda 表达式参数类型由编译推理得出,也可以显式的指定参数类型
Arrays.asList("a", "b", "c", "d").forEach((String e)  -> System.out.println(e));
  • Lambda 表达式是匿名函数,因为函数式接口有一个抽象方法,所以 Java 重写了它,若 Lambda 类型不能确定,需要加上强制类型转换
TestFunctionInterface1 t1 = (TestFunctionInterface1)()->System.out.println("hello");
testFunctionInterface.print();
  • 如果函数只有一个参数,可以省略圆括号,并且如果代码比较多,可以使用花括号括起来:
TestFunctionInterface2 t2 = name -> {System.out.println("my name is "+name);};
TestFunctionInterface3 t3 = (name,age) -> {System.out.println("my name is "+name+" and age "+age);};
  • 如果Lambda中的代码是一个表达式而不是一个声明,它就会被当作一个返回值
IntUnaryOperator addOne = x -> x + 1;
  • 使用 Lambda 表达式去排序一个集合,在 Java8 之前,排序一个集合的时候,需要用匿名内部类去实现 java.util.Comparator 接口:
// 匿名内部类方式:
List<String> list = Arrays.asList("a", "c", "b");
list.stream().sorted(new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
});

// Lambda 表达式方式:
List<String> list = Arrays.asList("a", "c", "b");
list.stream().sorted((p1,p2)->p1.compareTo(p2));
  • Lambda 表达式(匿名类) 在访问外部局部变量时,其实是拷贝了一份外部局部变量的副本,修改副本的值是不会影响到外部局部变量的值的(因为Java只有值拷贝,没有引用拷贝,而外部局部变量的引用与Lambda表达式内部变量的引用并非同一个),因此若欲想在 Lambda 表达式中修改外部局部变量的值,则会提醒需要将外部局部变量显式的声明为 final,以免开发者会误以为能够在 Lambda 表达式中修改外部局部变量的值
int number = 0;
IntStream.range(1, 3).forEach(i -> {
    // 若无修改外部局部变量的值的操作,则无需声明为 final
    System.out.println(number);
});
int number = 0; 
IntStream.range(1, 3).forEach(i -> {
    // 此处报错,Lambda 表达式中不能修改外部局部变量的值
    // 因为 Lambda 表达式中的变量是外部局部变量的副本拷贝,修改副本的值不会影响原变量的值
    // 需显示的声明 number 为 final
    number = number + 1;       
});

方法引用

  • 方法引用是用来直接访问类或者实例已存在的方法或构造方法,可以理解为 Lambda 简化写法,使用 :: 来引用
@FunctionalInterface
public interface Supplier<T> {
    T get();
}
 
class Car {
    //Supplier是jdk1.8的接口,这里和lamda一起使用了
    public static Car create(final Supplier<Car> supplier) {
        return supplier.get();
    }
 
    public static void collide(final Car car) {
        System.out.println("Collided " + car.toString());
    }
 
    public void follow(final Car another) {
        System.out.println("Following the " + another.toString());
    }
 
    public void repair() {
        System.out.println("Repaired " + this.toString());
    }
}
  • 构造器引用
Car car = Car.create( Car::new );
List< Car > cars = Arrays.asList( car );
  • 静态方法引用
cars.forEach( Car::collide );
  • 特定类任意对象方法引用
cars.forEach( Car::repair );
  • 特定对象的方法引用
Car police = Car.create( Car::new );
cars.forEach( police::follow );

相关文章

网友评论

    本文标题:Java8 函数式接口 与 Lambda 及 方法引用

    本文链接:https://www.haomeiwen.com/subject/owpctftx.html