2013-08-03 33 views
7

這是對另一個問題(Reuse code for looping through multidimensional-array)的跟進,其中我的具體問題已通過使用命令模式解決。我的問題是,我有多個方法對二維數組的每個元素執行操作 - 因此有很多重複的代碼。相反,有許多方法,像這樣的......命令模式如何被lambda表達式替換?

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表達式,怎麼會這樣縮短?一般情況如何? (對不起,我的英文很差)

回答

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

非常感謝你的回答。你能解釋一下「Arrays.stream」方法嗎? – subarachnid

+3

它只是返回[流](http://lambdadoc.net/api/index.html?java/util/stream/Stream.html):)你可以[嘗試](http://jdk8.java.net/ download.html)。 – aim