函数式接口

267 阅读1分钟

函数式接口

  • 有且仅有一个方法的接口
  • 可以使用 Lambda 简化

Function

  • 需要提供一个输入和一个输出
  • 可以理解为就是一个函数
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
    
}
  • 示例
public static void main(String[] args) {
    Function<String, String> function = o -> o;
    System.out.println(function.apply("hello world"));
}

Function<String, String> function = (o) -> {
    return o;
};

Predicate

  • 判断 断定性接口
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
}
  • 示例
Predicate<String > predicate= "hello"::equals;
System.out.println(predicate.test("test"));

Consumer

  • 消费型接口,只有一个参数,没有返回值
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
}
  • 示例
Consumer<String> consumer = System.out::println;
consumer.accept("hello");

Supplier

  • 供给型接口,没有参数,有一个返回值.
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}
  • 示例
Supplier<String> stringSupplier = () -> "hello";
System.out.println(stringSupplier.get());