public class B002 {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
System.out.println("Hello Lambda 2!!!");
}
};
r.run();
}
}
public class B002 {
public static void main(String[] args) {
Runnable r = () -> {
System.out.println("Hello Lambda~!")
};
r.run();
}
}
new Runnable() - 삭제
- Runnalbe 타입으로 참조 변수 r을 만들고 있어 new Runnalbe()은 컴파일러가 알아낼 수 있기 때문에 삭제
public void run() → ()
- Runnable 인터페이스가 가진 추상 메서드가 run() 메서드 단 하나이기 때문에 변경
'->' - 추가
- 람다의 구조는 (인자 목록) -> {로직}
- 단 한 줄로 표기되는 경우 블록 기호 {} 생략 가능
public class B005 {
public static void main(String[] args) {
MyFunctionalInterface mfi = (int a) -> { return a + a; };
int b = mfi.runSomething(5);
System.out.println(b);
}
}
@FunctionalInterface
interface MyFunctionalInterface {
public abstract int runSomething(int count);
}
@FunctionalInterface 어노테이션
컴파일러는 해당 인터페이스가 함수형 인터페이스의 조건에 맞는지 검사(하나의 추상 메서드만을 갖고 있는지 확인)
람다식을 메서드의 인자로도 사용 가능 - 코드 블록을 메서드의 인자로 전달
람다식을 단 한번만 사용한다면 변수에 할당할 이유가 없다.
public class B009 {
public static void main(String[] args) {
MyFunctionalInterface mfi = todo();
int result = mfi.runSomething(3);
System.out.println(result);
}
public static MyFunctionalInterface todo() {
return num -> num * num;
}
}
| 함수형 인터페이스 | 추상 메서드 | 용도 |
|---|---|---|
| Runnable | void run() | 실행 할 수 있는 인터페이스 |
| Supplier | T get() | 제공 할 수 있는 인터페이스 |
| Consumer | void accept(T t) | 소비 할 수 있는 인터페이스 |
| Function<T, R> | R apply(T t) | 입력을 받아서 출력 할 수 있는 인터페이스 |
| Predicate | Boolean test(T t) | 입력을 받아 참/거짓을 단정 할 수 있는 인터페이스 |
| UnaryOperator | T apply(T t) | 단항(Unary) 연산 할 수 있는 인터페이스 |
| BiConsumer<T, U> | void accept(T t, U u) | 이항 소비자 인터페이스 |
| BiFunction<T, U, R> | R apply(T t, U u) | 이항 함수 인터페이스 |
| BiPredicate<T, U> | Boolean test(T t, U u) | 이항 단정 인터페이스 |
| BinaryOperator<T, T> | T apply(T t, T t) | 이항 연산 인터페이스 |