Search code examples
javalistjava-17

How do I create a List of functions in Java?


How can I create an array or List of functions in Java 17 (or similar)?

Expected hypothetical usage:

    var myListOfFunctions = List.of(this::myFunction, MyClass::someOtherFunction);

I get the following error:

Object is not a functional interface

I intend to stream the functions and pass them the same data.


Solution

  • First, create a functional interface that represents the common signature of all the functions. Note: there may be an interface from the java.util.function package that can be used to represent the signature, so it may not be necessary to create a new interface.

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

    Then, create a List of that type.

    List<MyFunction> functions = List.of(this::myFunction, MyClass::someOtherFunction);