기존의 객체 지향이 아닌 함수 지향 프로그래밍 방법
람다식이란?
익명 함수(Anonymous Function)를 이용해서 익명 객체를 생성하기 위한 식
[ 기존 방법 ]
InterfaceType 변수 --- 할당(대입) ---> Interface 구현
[ 람다식 방법 ]
InterfaceType 변수 --- 할당(대입) ---> Lambda Expressions
람다식 구현
1. 매개변수와 실행문만으로 작성한다(접근자, 반환형, return 키워드 생략)
public interface LambdaInterface {
public void method(String s1, String s2, String s3);
}
public static void main(String[] args) {
LambdaInterface li = (String s1, String s2, String s3) -> {System.out.println(s1 + " " + s2 + " " + s3);};
li.method("Hello", "java", "World");
}
---- result ----
Hello java World
2. 매개변수가 1개이거나 타입이 같을 때, 타입을 생략할 수 있다
public interface LambdaInterface {
public void method(String s1);
}
public static void main(String[] args) {
LambdaInterface li = (s1) -> {System.out.println(s1);};
li.method("Hello");
}
---- result ----
Hello
3.실행문이 1개일 때, '{ }'를 생략할 수 있다
public interface LambdaInterface {
public void method(String s1);
}
public static void main(String[] args) {
LambdaInterface li = (s1) -> System.out.println(s1);
li.method("Hello");
}
---- result ----
Hello
4. 매개변수와 실행문이 1개일 때, '( )'와 '{ }'를 생략할 수 있다
public interface LambdaInterface {
public void method(String s1);
}
public static void main(String[] args) {
LambdaInterface li = s1 -> System.out.println(s1);
li.method("Hello");
}
---- result ----
Hello
5. 매개변수가 없을 때, '( )'만 작성한다
public interface LambdaInterface {
public void method();
}
public static void main(String[] args) {
LambdaInterface li = () -> System.out.println("no parameter");
li.method();
}
---- result ----
no parameter
6. 반환 값이 있는 경우
public interface LambdaInterface {
public int method(int x, int y);
}
public static void main(String[] args) {
// 데이터 타입이 같기 때문에 int 생략!!
LambdaInterface li = (x, y) -> {
int result = x + y;
return result;
};
System.out.printf("li.method(10,20) : %d\n", li.method(10,20));
}
---- result ----
li.method(10,20) : 30
'Study > Java' 카테고리의 다른 글
[Java] Collections (0) | 2020.07.03 |
---|---|
[Java] 문자열 클래스(String, StringBuilder, StringBuffer) (0) | 2020.07.03 |
[Java] 인터페이스와 추상클래스 (0) | 2020.07.03 |
[Java] 내부(inner) 클래스 & 익명(Anonymous) 클래스 (0) | 2020.07.03 |
[Java] 상속, Object & Super 클래스 (0) | 2020.07.03 |
댓글