fedorSmirnov fedorSmirnov -4 years ago 389
Java Question

Java function as method parameter

I am working with a system represented as a graph. I frequently need to traverse the graph in a certain fashion and apply different operations on the nodes passed along the way. I would like to implement the traverse logic in a class which then will get the operation that has to be applied as an input parameter of the method it provides. Something like this:

class GraphTraverse{

public static void traverseAndApplyOperation(Graph graph, Node startNode, Function operationToApply){

// go through the graph and apply the input function (specified somewhere else) on the passed nodes

}
}


Does Java provide a possibility to pass methods as input parameters and if so, what would be the proper syntax to do it?

Answer Source

Java 8 and beyond

Java 8 provides nice ways of doing so with predefined interfaces in java.util.function, depending on the type of function you want.

In your case, you're probably looking for a function that takes a Node and does not return anything. In Java 8, this is called a Consumer<Node>.

Declaration

public static void traverseAndApplyOperation(Graph graph, Node startNode, Consumer<Node> operationToApply) {
    // traversal logic with current node 'node'
    operationToApply.accept(node); // use it this way
}

Usage

With a lambda expression:

traverseAndApplyOperation(graph, startNode, node -> { /*do something here*/});

Or even better, if you have a static method static void MyClass.myMethod(Node), you can directly reference it:

traverseAndApplyOperation(graph, startNode, MyClass::myMethod);

It also works if you have a non-static 0-arg method in the Node class:

traverseAndApplyOperation(graph, startNode, Node::myMethod);

Java 7 and below

Just define your own interface with a single method, similar to Java 8's Consumer<Node>.

public interface NodeConsumer {
    void accept(Node node);
}

Then you can't instantiate it with a lambda but you can still use the old-fashioned way:

traverseAndApplyOperation(graph, startNode, new NodeConsumer() {
    @Override
    public void accept(Node node) {
        // do something here
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download