This is kind of a follow-up to another question (Reuse code for looping through multidimensional-array) where my specific problem was resolved by using the command-pattern. My problem was, that I had multiple methods performing operations on every element of a two-dimensional array - and therefore a lot of duplicate code. Instead of having many methods like so...
void method() {
    for (int i = 0; i < foo.length; i++) {
        for (int j = 0; j < foo[i].length; j++) {
            // perform specific actions on foo[i][j];
        }
    }
}
... I solved it like this:
interface Command {
    void execute(int i, int j);
}
void forEach(Command c) {
    for (int i = 0; i < foo.length; i++) {
        for (int j = 0; j < foo[i].length; j++) {
            c.execute(i, j);
        }
    }
}
void method() {
    forEach(new Command() {
        public void execute(int i, int j) {
            // perform specific actions on foo[i][j];
        }
    });
}
Now if we had lambda expressions in Java, how could this be shortened? How would that look like in general? (Sorry for my poor English)
In a classic implementation, the command pattern requires implementing four components: the Command, the Receiver, the Invoker, and the Client.
The Lambda-enabled Command Pattern.
Lambda expressions allow passing a function as an input parameter for another function, which was not possible earlier. In short, lambdas can replace anonymous classes, making the code readable and easy to understand. A lambda expression consists of two parts separated by the “->” operator.
A Command pattern is an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver. (A sender is an object that invokes an operation, and a receiver is an object that receives the request to execute a certain operation.
Here simple example with Java 8 lamdas. If you change a bit Command class so it will look like this:
    @FunctionalInterface
    interface Command {
        void execute(int value);
    }
Here it will accept value from sub array. Then you could write something like this:
    int[][] array = ... // init array
    Command c = value -> {
         // do some stuff
    };
    Arrays.stream(array).forEach(i -> Arrays.stream(i).forEach(c::execute));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With