Lambda 함수
Lambda의 특징
커링 예제
class Function {
public int add_numbers(int x, int y) {
return x + y;
}
}
함수형 인터페이스 : 구현해야할 메서드가 하나만 있는 인터페이스
@FunctionalInterface // 구현해야할 추상 메서드가 하나만 정의된 인터페이스
public interface Math {
public int Calc(int first);
}
public class main {
public static void main(String[] args) {
Function function = new Function();
Math add_4= (first) -> function.add_numbers(first, 4);
System.out.println(add_4.Calc(4));
}
}
장점
지연 연산 (Lazy Evaluation) : 결과값이 필요할 때 까지 연산을 늦추는 기법
단점
Runnable 을 이용하여 Thread를 만들어 실행해보겠습니다.
public class LambdaExam1 {
public static void main(String[] args) {
new Thread(new Runnable(){public void run(){
for(int i = 0; i < 10; i++){
System.out.println("hello");
}
}}).start();
}
}
메서드만 전달할 수 있다면, 더 편하게 프로그래밍을 할 수 있다.
Lambda 식을 활용해 이를 해결한 코드
public class LambdaExam1 {
public static void main(String[] args) {
new Thread(()->{
for(int i = 0; i < 10; i++){
System.out.println("hello");
}
}).start();
}
}
2개의 값을 매개변수로 받아, 비교하여 어떤 값이 더 큰지 구하는 인터페이스
// 함수형 인터페이스 : 구현해야할 메서드가 하나만 있는 인터페이스
@FunctionalInterface
public interface Compare {
public int compareTo(int value1, int value2);
}
Compare 인터페이스를 사용하는 클래스
public class CompareExam {
public static void exec(Compare compare) {
int k = 10;
int m = 20;
int value = compare.compareTo(k, m);
if (value < 0) {
System.out.println("m 이 더 큽니다.")
} else {
System.out.println("k 가 더 큽니다.")
}
}
public static void main(String[] args) {
exec((i, j) -> {
return i - j;
})
}
}
출력
m이 더 큽니다.