개념 공부/(개발) 01. Java
[Java] 07-3. 기본 제공 함수형 인터페이스
hoonii2
2022. 12. 23. 17:59
1. 개요
: 기본 API 에서 함수형 인터페이스는 java.util.function 패키지에 정의
2. FunctionalInterface 어노테이션
: @FunctionalInterface 는 개발자들에게 해당 인터페이스가 함수형 인터페이스라는 것을 알려주고 컴파일러가 SAM 여부를 체크
@FunctionalInterface
interface Calculation {
Integer apply(Integer x, Integer y);
}
3. Function
: 특정 오브젝트를 받아서 특정 오브젝트를 리턴하는 메소드
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
static <T> Function<T, T> identity() {
return t -> t;
}
}
- Compose
: Before 메소드를 실행하고 결과를 받아 현재 메소드를 실행
: 제네릭은 처음 input 과 마지막 output 타입 정의
Function<Integer, String> intToString = Objects::toString;
Function<String, String> quote = s -> "'" + s + "'";
Function<Integer, String> quoteIntToString = quote.compose(intToString);
System.out.println(quoteIntToString.apply(5)); // '5'
- Andthen
: Compose 와 반대로 현재 메소드 실행 후 매개변수 람다를 실행
Function<String, String> upperCase = v -> v.toUpperCase();
String result = upperCase.andThen(s -> s + "abc").apply("a");
System.out.println(result); // Aabc