본문 바로가기

6. With IT

Java8 람다식


람다식(lambda expression)


[정의]

- 프로그래밍에서 식별값 없이 실행할 수 있는 함수 표현 방법


[지원 언어]

- Ruby, C#, Python에서 이미 사용중


[장점]

- 대리자(Delegate)와 제네릭 메서드의 복잡한 식을 간결하게 줄여줄 수 있다.

- 연산자를 이용하여, 익명 메서드(Anonymous Method)의 여러줄의 코드를 단 한줄의 코드로 줄여줄 수가 있다.


[문법]

(인자 목록) -> { 구문 }


[사용 예 1]

Java 7

public class AsyncHelloWorld {
    public static class HelloWorld implements Runnable {

@Override

public void run() {
    System.out.println("Hello World!");

}

}


public static void main(String[] args) {

new Thread(new HelloWorld()).start();

}

}


Java 8

public class AsyncHelloWorld {
    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println("Hello World!");

}).start();

}

}


[사용 예 2]

[Java7]

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

System.out.println("button clicked");

}

});


[Java8]

button.addActionListener(event -> System.out.println("button clicked"));