Đinh Carabus
Đinh Carabus

Reputation: 3494

How could the command pattern be replaced by lambda expressions?

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)

Upvotes: 7

Views: 2586

Answers (1)

aim
aim

Reputation: 1493

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));

Upvotes: 10

Related Questions