Java 函数式接口

函数式接口

Functional Interface 就是一个有且只有一个抽象方法,但是可以有多个非抽象方法的接口。

  • 函数式接口可以被隐式的转换为lambda表达式
  • 不能使用以下类型方法来声明一个函数式接口:默认方法(default)、静态方法、从Object类继承的方法

函数式接口格式

@FunctionalInterface
public interface MyInterface {
  public void method(String s);
}

// 使用 lambda 表达式实现该接口
MyInterface myInterface = (s) -> System.out.println(s);

// 上面的过程相当于
MyInterface myInterface = new MyInterface() {
  @Override
  public void method(String s) {
    // TODO Auto-generated method stub
    System.out.println(s);
  }
};

函数式编程

使用Lambda表达式作为参数传递

public class RunnableExample {
  private static void start(Runnable task) {
    new Thread(task).start();
  }
  
  public static void main(String[] args) {
    start(() -> System.out.println("Execute thread."))
  }
}

使用Lambda表达式作为返回值

public class LambdaReturnExample {
  public Comparator<String> comparator() {
    return (o1, o2) -> o2.length() - o1.length();
  }
  
  // 上面的lambda等价于
  public Comparator<String> comparator() {
    return new Comparator<String>() {
      @Override
      public int compare(String o1, String o2) {
        return o2.length() - o1.length();
      }
    }
  }
}

通用函数式接口

使用类型参数与函数式接口创建通用函数式接口。

@FunctionalInterface
public interface Comparator<T> {
  int compare(T o1, T o2);
}

常用函数式接口

Supplier 接口

@FunctionalInterface
public interface Supplier<T> {

  /**
   * 编译器自动给方法加上 public abstract
   * 产生一个 T 类型数据
   */
  T get();
}

Consumer 接口

@FunctionalInterface
public interface Consumer<T> {
  /**
   * 与 Supplier相反,Consumer消费一个 T 类型数据
   */
  void accept(T t);
}

Predicate 接口

@FunctionalInterface
public interface Predicate<T> {
  /**
   * 根据给定参数计算布尔值
   */
  boolean test(T t);
  
  // 逻辑与
  default Predicate<T> and(Predicate<? super T> other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) && other.test(t);
  }
  
  // 逻辑非
  default Predicate<T> negate() {
    return (t) -> !test(t);
  }
  
  // 逻辑或
  default Predicate<T> or(Predicate<? super T> other) {
    Objects.requireNonNull(other);
    return (t) -> test(t) || other.test(t);
  }
  
  // 返回 Predicate,可以判断两个参数是否相等
  static <T> Predicate<T> isEqual(Object targetRef) {
    return (null == targetRef)
      ? Objects::isNull
        : object -> targetRef.equals(object);
  }
}

Function 接口

@FunctionalInterface
public interface Function<T, R> {
  /**
   * 根据 T 类型数据,得到 R 类型数据
   */
  R apply(T t);
}

参考文章

[1] Java 8 函数式接口

[2] 详解Java 8 函数式接口

posted @ 2022-07-02 07:58  ylyzty  阅读(44)  评论(0编辑  收藏  举报