람다식(Lamda Expression)이란
람다 함수는 Java8부터 도입되었으며, 클래스, 객체를 생성하고 메소드를 호출할 필요 없이 메소드의 역할을 대신할 수 있는 익명 함수를 지칭하는 용어이다.
람다식의 장단점
장점
단점
기존 문법과 람다식
기존 문법
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello java");
}
}).start();
람다식
new Thread(()->{
System.out.println("hello java");
}).start();
기본 람다식
먼저 작성한 코드로 설명을 해보겠다.
LamdaInterface1.java
package lamdainteface;
public interface LamdaInterface1 {
public void method(String s1, String s2, String s3);
}
MainClass.java
LamdaInterface1 li1 = (String s1, String s2, String s3) -> {
System.out.println(s1 + " " + s2 + " " + s3 + " ");
};
li1.method("Hello", "Lamda", "!!\n");
Lamdainterface1 이라는 인터페이스에서 매개변수 String s1, String s2, String s3가 있는 method를 선언하였다.
MainClass 에서 LamdaInterface1에 대한 람다식을 구현하기 위한 식은 다음과 같다.
LamdaInterface1 참조변수 = (매개변수 1, 매개변수 2, 매개변수 3) -> {
System.out.println(매개변수 1 + " " + 매개변수 2 + " " + 매개변수 3 + " ");};
참조변수.인터페이스에 선언한 메서드명(매개변수 1에 넣고 싶은 값, 매개변수 2에 넣고 싶은 값, 매개변수 3에 넣고 싶은 값);
람다식에서의 예외 상황
구조는 기본 람다식과 같다.
package lamdainteface;
public class MainClass {
public static void main(String[] args) {
// 기본 람다식
LamdaInterface1 li1 = (String s1, String s2, String s3) -> {
System.out.println(s1 + " " + s2 + " " + s3 + " ");
};
li1.method("Hello", "Lamda", "!!\n");
// 매개변수 1개일 때, 타입 생략 가능
LamdaInterface2 li2 = (s1) -> {
System.out.println(s1);
};
li2.method("only one parameter\n");
// 모든 매개변수가 타입이 같을 때, 타입 생략 가능
LamdaInterface1 li3 = (s1, s2, s3) -> {
System.out.println(s1 + " " + s2 + " " + s3 + " ");
};
li3.method("all parameter", "same type parameter", "can use none-type\n");
// 실행문이 1개일 때 "{ }" 생략 가능
LamdaInterface1 li4 = (s1, s2, s3) ->
System.out.println(s1 + " " + s2 + " " + s3 + " ");
li4.method("Only one executable statement", "can use", "non-{ }\n");
// 매개변수 1개와 실행문이 1개일 때 "( )", "{ }" 생략 가능
LamdaInterface2 li5 = s1 ->
System.out.println(s1);
li5.method("Only one parameter and only one executable statment can use non-( ), { }\n");
// 매개변수가 없을 때
Lamdainterface3 li6 = () -> {
System.out.println("none-parameter");
};
li6.method();
}
}