Java:通用函数X-> Y接口

Alb*_*ert 10 java interface function

我需要一个界面,如:

interface Function<X,Y> {
    Y eval(X obj);
}
Run Code Online (Sandbox Code Playgroud)

Java中是否有这样的东西,或者我需要定义自己的东西吗?

Nat*_*hes 13

查看Guava,它有一个Function接口:

public interface Function<F, T> {
  /**
   * Applies the function to an object of type {@code F}, resulting in an object of     type {@code T}.
   * Note that types {@code F} and {@code T} may or may not be the same.
   *
   * @param from the source object
   * @return the resulting object
   */
  T apply(@Nullable F from);

  /**
   * Indicates whether some other object is equal to this {@code Function}. This     method can return
   * {@code true} <i>only</i> if the specified object is also a {@code Function} and, for every
   * input object {@code o}, it returns exactly the same value. Thus, {@code
   * function1.equals(function2)} implies that either {@code function1.apply(o)} and {@code
   * function2.apply(o)} are both null, or {@code function1.apply(o).equals(function2.apply(o))}.
   *
   * <p>Note that it is always safe <i>not</i> to override {@link Object#equals}.
   */
  boolean equals(@Nullable Object obj);
 }
Run Code Online (Sandbox Code Playgroud)


Jor*_*orn 6

不幸的是,核心Java库中没有这样的东西.因此,许多库定义了自己的类似功能的接口.如果您恰好使用了这样的库,则可以重新使用它使用的功能.


小智 3

有一个像这样的内置接口,尽管它只兼容 Java 8 及以上版本。你可以在这里找到它。

来自 Java 文档:

public interface Function<T,R>

表示一个函数,它接受一个参数并产生一个结果。

这是一个函数式接口,其函数式方法为apply(Object)

类型参数:
T - 函数输入的类型
R- 函数结果的类型