7

这是对另一个问题( Reuse code for looping through multidimensional-array )的跟进,我的具体问题是通过使用命令模式解决的。我的问题是,我有多种方法对二维数组的每个元素执行操作 - 因此有很多重复的代码。而不是有很多这样的方法......

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];
        }
    }
}

...我这样解决了:

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

现在,如果我们在 Java 中有 lambda 表达式,如何缩短它呢?一般情况下会是什么样子?(对不起我的英语不好)

4

1 回答 1

8

这里是 Java 8 lamdas 的简单示例。如果你改变一个位Command类,它会看起来像这样:

    @FunctionalInterface
    interface Command {
        void execute(int value);
    }

在这里它将接受来自子数组的值。然后你可以写这样的东西:

    int[][] array = ... // init array
    Command c = value -> {
         // do some stuff
    };
    Arrays.stream(array).forEach(i -> Arrays.stream(i).forEach(c::execute));
于 2013-08-03T20:22:03.343 回答