익명 함수를 지칭하는 용어
함수를 단순하게 표현하는 방법
구현해야 할 추상 메소드가 하나만 정의된 인터페이스를 가리킴
//인자 x, y를 받아들여 x+y를 리턴하는 람다식 만들기
//함수형 인터페이스
@FunctionalInterface
interface MyFunction {
int calc(int x, int y);
}
public class LambdaEx {
public LambdaEx() {
// MyFunction f = new MyFunction() {
//
// @Override
// public int calc(int x, int y) {
// return x+y;
// }
//
// };
MyFunction f1 = (x, y) -> {return x+y;};
System.out.println("f1의 결과: " + f1.calc(22, 100));
MyFunction f2 = (x, y) -> {return x-y;};
System.out.println("f2의 결과: " + f2.calc(99, 9));
}
public static void main(String[] args) {
new LambdaEx();
}
}
// 출력 결과
// f1의 결과 : 122
// f2의 결과 : 90
//인자 x를 받아들여 제곱을 리턴하는 람다식 만들기
//함수형 인터페이스
@FunctionalInterface
interface Myfunction2 {
int calc(int x);
}
public class LambdaEx2 {
public LambdaEx2() {
//Myfunction2 fsquare = (x) -> {return x*x;};
Myfunction2 fsquare = (x) -> {return x*x;};
System.out.println("fsquare의 결과: "+fsquare.calc(5));
}
public static void main(String[] args) {
new LambdaEx2();
}
}
// 출력 결과
// fsquare의 결과 : 25
//매개변수가 없는 람다식 만들기
//함수형 인터페이스
@FunctionalInterface
interface MyFunction3 {
void print();
}
public class LambdaEx3 {
public LambdaEx3() {
MyFunction3 fprint = () -> {System.out.println("Yoon's Dev");};
fprint.print();
}
public static void main(String[] args) {
new LambdaEx3();
}
}
//메소드의 인자로 람다식 전달
//함수형 인터페이스
@FunctionalInterface
interface MyFunction4 {
int calc(int x, int y);
}
public class LambdaEx4 {
//메소드 정의 (메소드의 인자로 람다식 전달)
static void printMultiply(int x, int y, MyFunction4 f) {
System.out.println("실행 결과: " + f.calc(x, y));
}
public LambdaEx4() {
printMultiply(100, 100, (x, y) -> {return x * y;});
}
public static void main(String[] args) {
new LambdaEx4();
}
}
List<String> list = List.of("Peter", "Thomas", "Edvard", "Gerhard");
// 람다식
list.forEach(item -> System.out.println(item));
// 더블콜론
list.forEach(System.out::println);