跳至主要內容

函数式接口

Jin小于 1 分钟

函数式接口

1、函数式接口的定义:

  • 任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。对于函数式接口,我们可以通过lambda表达式来创建该接口的对象。

    public interface Runnable{
      public abstract void run();
    }
    
    函数式接口名称方法名称参数返回值
    Runnablerun无参数无返回值
    Functionapply1个参数有返回值
    Consumeaccept1个参数无返回值
    Supplierget没有参数有返回值
    Biconsumeraccept2个参数无返回值

2、常见的函数式接口

2.1. Runnable

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

2.2. Function

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

2.3. Consumer

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

2.4. Supplier

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

2.5. Biconsumer(Bi代表两个的意思,我们要传入两个参数,在上面的案例中是v和e)

@FunctionalInterface
public interface BiConsumer<T, U> {
    void accept(T t, U u);

}
贡献者: Jin