파트-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 → 현재).
0 조회
Back to Blog

관련 글

더 보기 »

파트-3 Functional Interface (Consumer)

Consumer Consumer는 java.util.function에 있는 함수형 인터페이스입니다. 하나의 입력을 받아 반환값이 없는 연산을 나타냅니다. 핵심 메서드 java void a...

AWS 클라우드 채택 프레임워크

AWS Cloud Adoption Framework 🚀☁️ 온프레미스에서 작업하고 클라우드로 워크로드를 이전하는 방법을 고민하고 있나요? 이는 매우 흔한 질문입니다;...