파트-4 함수형 인터페이스(Function)
발행: (2026년 3월 3일 오후 06:09 GMT+9)
2 분 소요
원문: Dev.to
Source: Dev.to
Functional Interface: Function
java.util.function에 있는 함수형 인터페이스로, 변환을 나타냅니다: 입력 타입 T를 받아 출력 타입 R을 생성합니다.
Core Method
R apply(T t);
Extra Methods
andThen(Function after)
현재 함수 이후에 실행될 다른 함수를 연결합니다.
Function lengthFinder = str -> str.length();
Function square = n -> n * n;
Function lengthSquared = lengthFinder.andThen(square);
System.out.println(lengthSquared.apply("Java")); // 16
compose(Function before)
현재 함수 이전에 다른 함수를 적용합니다.
Function square = n -> n * n;
Function toString = n -> "Result: " + n;
Function squareThenString = toString.compose(square);
System.out.println(squareThenString.apply(5)); // Result: 25
Example: Function Order Demo
import java.util.function.Function;
public class FunctionOrderDemo {
public static void main(String[] args) {
Function add2 = n -> n + 2;
Function multiply3 = n -> n * 3;
// andThen → 현재 함수 먼저, 그 다음 after
System.out.println(add2.andThen(multiply3).apply(5));
// (5 + 2) * 3 = 21
// compose → before 먼저, 그 다음 현재 함수
System.out.println(add2.compose(multiply3).apply(5));
// (5 * 3) + 2 = 17
}
}
When to Use andThen vs. compose
andThen은 현재 함수를 먼저 적용하고 그 다음 다른 함수를 적용하고 싶을 때 충분합니다 (현재 → after).compose은 메인 함수를 적용하기 전에 입력을 전처리해야 할 때 유용합니다 (before → 현재).