- 타겟 타입 : 람다식이 대입될 인터페이스 (익명 구현 객체를 만들 때 사용할 인터페이스)
인터페이스 변수 = 람다식;
- 함수적 인터페이스 (@FunctionalInterface)
: 하나의 추상 메소드가 선언된 인터페이스
: @FunctionalInterface : 두 개 이상의 추상 메소드가 선언되면 컴파일 오류가 발생하도록 하는 어노테이션 → 선택사항
package sec03.exam01_no_arguments_no_return_YJ;
@FunctionalInterface
public interface MyFunctionalInterface {
public void method();
//public void method2(); //함수적 인터페이스(FunctionalInterfac - 추상메소드 한개만 허용하므로 컴파일 오류 발생
}
1. 매개 변수와 리턴값이 없는 람다식
함수적 인터페이스
package sec03.exam01_no_arguments_no_return_YJ;
@FunctionalInterface
public interface MyFunctionalInterface {
public void method();
//public void method2(); //함수적 인터페이스(FunctionalInterfac - 추상메소드 한개만 허용하므로 컴파일 오류 발생
}
람다식
package sec03.exam01_no_arguments_no_return_YJ;
public class MyFunctionalInterfaceExample {
public static void main(String[] args) {
MyFunctionalInterface fi; //인터페이스 타입의 변수
fi = () -> {
String str = "method call1";
System.out.println(str);
};
fi.method();
fi = () -> { System.out.println("method call2"); };
fi.method();
fi = () -> System.out.println("method call2"); //실행문이 한 개일 경우 중괄호 {} 생략 가능
fi.method();
}
}
method call1
method call2
method call2
2. 매개 변수가 있는 람다식
함수적 인터페이스
package sec03.exam02_arguments_YJ;
@FunctionalInterface
public interface MyFunctionalInterface {
public void method(int x);
}
람다식
package sec03.exam02_arguments_YJ;
public class MyFunctionalInterfaceExample {
public static void main(String[] args) {
MyFunctionalInterface fi; //인터페이스 타입의 변수 선언
fi = (x) -> {
int result = x * 5;
System.out.println(result);
};
fi.method(2);
fi = (x) -> { System.out.println(x * 5); };
fi.method(2);
fi = x -> System.out.println(x * 5);
fi.method(2);
}
}
10
10
10
3. 리턴값이 있는 람다식
함수적 인터페이스
package sec03.exam03_return_YJ;
@FunctionalInterface
public interface MyFunctionalInterface {
public int method(int x, int y);
}
람다식
package sec03.exam03_return_YJ;
public class MyfunctionalInterfaceExample {
public static void main(String[] args) {
MyFunctionalInterface fi; //인터페이스 타입(타겟 타입)의 변수 선언
fi = (x, y) -> {
int result = x + y;
return result;
};
//람다식을 함수적 인터페이스의 추상메소드명으로 호출
System.out.println(fi.method(2, 5));
fi = (x, y) -> { return x + y; };
System.out.println(fi.method(2, 5));
fi = (x, y) -> x + y; //return문만 있을 경우 중괄호 {}와 return 생략 가능
System.out.println(fi.method(2, 5));
fi = (x, y) -> sum (x, y); //sum 메소드 사용
System.out.println(fi.method(2, 5));
}
public static int sum(int x, int y) { //sum 메소드 선언
return (x + y);
}
}
7
7
7
7
'Java > 14. 람다식 (Lambda Expressions)' 카테고리의 다른 글
Day 19 : 표준 API의 함수적 인터페이스 - Supplier (0) | 2021.11.12 |
---|---|
Day 19 : 표준 API의 함수적 인터페이스 - Consumer (0) | 2021.11.12 |
Day 19 : 표준 API의 함수적 인터페이스 (0) | 2021.11.12 |
Day 19 : 클래스 멤버와 로컬 변수 사용 (0) | 2021.11.12 |
Day 19 : 람다식(Lamda Expressions) (0) | 2021.11.12 |