2013-08-03 5 views
7

이것은 다른 질문 (Reuse code for looping through multidimensional-array)의 후속 작업으로, command-pattern을 사용하여 특정 문제가 해결되었습니다. 내 문제는 2 차원 배열의 모든 요소에 대해 작업을 수행하는 여러 가지 방법이 있다는 것입니다. 따라서 중복 된 코드가 많습니다. 대신 명령 패턴을 람다 식으로 어떻게 대체 할 수 있습니까?

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

을 우리가 자바에서 람다 표현식이 있다면 이제, 어떻게이 단축 될 수 있을까? 그게 대체 어떻게 생겼어? (나의 가난한 영어로 유감스럽게 생각합니다)

답변

8

자바 8 람다를 사용한 간단한 예입니다. 이 같이 표시됩니다 있도록 조금 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

그냥 [Stream] (http://lambdadoc.net/api/index.html?java/util/stream/Stream.html)을 반환합니다 :) [try] (http://jdk8.java.net/ download.html)을 다운로드하십시오. – aim