(타입 매개변수...) -> {
실행문 ..
}
() -> {}
package chapter15;
public class LambdaFunctionEx {
public static void main(String[] args) {
// 람다식
public static void main(String[] args) {
InterfaceEx ie1 = (int x, int y) -> x + y;
InterfaceEx ie2 = (int x, int y) -> x - y;
InterfaceEx ie3 = (int x, int y) -> x * y;
InterfaceEx ie4 = (int x, int y) -> x / y;
System.out.println(ie1.calc(5, 4));
System.out.println(ie2.calc(5, 4));
System.out.println(ie3.calc(5, 4));
System.out.println(ie4.calc(5, 4));
}
}
}
// 함수적 인터페이스
interface InterfaceEx {
public int calc(int x, int y);
}
package chapter15;
public class LambdaEx {
public static void main(String[] args) {
LambdaInterface li = () -> {
String str = "메서드 출력";
System.out.println(str);
};
li.print();
}
}
interface LambdaInterface {
void print();
//void print2(); // 오류발생
}
@FunctionalInterface
package chapter15;
public class LambdaEx3 {
public static void main(String[] args) {
LambdaInterface3 li3 = (String name) -> {
System.out.println("제 이름은 "+name+"입니다.");
};
li3.print("홍길동");
}
}
@FunctionalInterface
interface LambdaInterface3 {
void print(String name);
}
매개변수와 리턴값 사용
package chapter15;
public class LambdaEx4 {
public static void main(String[] args) {
LambdaInterface4 f4 = (x,y) -> {
return x * y;
};
System.out.println("두 수의 곱 : " + f4.cal(3, 2));
f4 = (x, y) -> x + y;
System.out.println("두 수의 합 : " + f4.cal(3, 2));
f4 = (x, y) -> { return x/y; };
System.out.println("두 수의 몫 : " + f4.cal(5, 2));
f4 = (x, y) -> x%y;
System.out.println("두 수의 나머지 : " + f4.cal(5, 2));
f4 = (x,y) -> sum(x, y);
System.out.println("두 수의 합(sum()) : " + f4.cal(3, 2));
}
static int sum(int x, int y) {
return x+y;
}
}
@FunctionalInterface
interface LambdaInterface4 {
int cal(int x, int y);
}