pass function as argument java code example

Example 1: java pass method as parameter

public void setAllComponents(Component[] myComponentArray, Consumer<Component> myMethod) {
    for (Component leaf : myComponentArray) {
        if (leaf instanceof Container) { 
            Container node = (Container) leaf;
            setAllComponents(node.getComponents(), myMethod);
        } 
        myMethod.accept(leaf);
    } 
}

Example 2: java pass method as parameter

setAllComponents(this.getComponents(), this::changeColor);
setAllComponents(this.getComponents(), this::changeSize);

Example 3: java pass method as parameter

public interface Function4<A, B, C, D, R> {

    R apply(A a, B b, C c, D d);
}

Tags:

Java Example