如何在 Java 中创建函数列表?

Ahm*_*fik 0 java list java-17

如何在 Java 17(或类似版本)中创建数组或函数列表?

预期的假设用途:

    var myListOfFunctions = List.of(this::myFunction, MyClass::someOtherFunction);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

对象不是函数式接口

我打算流式传输这些函数并向它们传递相同的数据。

hev*_*ev1 5

首先,创建一个代表所有函数的公共签名的函数接口。注意:包中可能有一个接口java.util.function可用于表示签名,因此可能不需要创建新接口。

// for example
@FunctionalInterface
interface MyFunction {
    int f(int a, int b); // this must match the signature of each function
}
Run Code Online (Sandbox Code Playgroud)

然后,创建List该类型的一个。

List<MyFunction> functions = List.of(this::myFunction, MyClass::someOtherFunction);
Run Code Online (Sandbox Code Playgroud)