본 포스팅의 목적
- 람다식을 처음 접했을 때, 굉장히 익숙치 않아서 친해지기까지 꽤 오랜 시간이 걸렸다.
- 람다식을 이해하기 위해서는 메서드는 기본이고, 내부 클래스와 익명 객체, 함수형 인터페이스의 이해가 필수적이다.
- 이러한 복합적인 개념들이 한 데 모여 간소화한 것이 람다식의 형태인데, 자바 초보자의 입장에서 람다식을 처음 보면 매우 낯설게 느껴진다.
- 따라서, 본 포스팅에서는 예제와 모식도를 활용하여 낯선 람다식과 함수형 인터페이스를 친숙하게 느껴보고자 한다.
//1. 함수형 인터페이스
@FunctionalInterface
interface MyFunction {
//단 하나의 추상메서드
public abstract int max(int a, int b);
}
//2. 익명객체 : 함수형 인터페이스의 추상메서드를 구현, 참조변수의 타입은 함수형 인터페이스
MyFunction myFunction = new MyFunction() {
public int max(int a, int b) {
return a > b ? a : b;
}
};
//3. 람다식 : 위의 익명객체를 간단히 표현할 뿐, 익명객체와 동일하다.
MyFunction myFunction = (a, b) -> a > b ? a : b;
//4. 람다식 호출 : 람다식의 메서드는 이름이 없으므로, 구현한 함수형 인터페이스의 메서드 이름을 사용한다.
int bigNum = myFunction.max(5, 10); //bigNum=10
//함수형 인터페이스 Supplier
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
//사용 예시
Supplier<Integer> sup = () -> (int)(Math.random()*100 + 1);
int random = sup.get(); //난수
//함수형 인터페이스 Consumer
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
//사용 예시
Consumer<Integer> con = (i) -> System.out.println(i);
c.accept(1234); //1234
//함수형 인터페이스 Function
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
//사용 예시
Function<Integer, Integer> func = (i) -> (i/10)*10;
int num = func.apply(15); // num=10
//함수형 인터페이스 Predicate
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
//사용 예시
Predicate<Integer> pre = (i) -> i % 2 == 0;
boolean isEven = pre.test(15); //isEven=false
참고서적
- 자바의 정석(남궁성 저)
항상 응원합니다요~