Function

sungs·2025년 6월 29일

자바

목록 보기
24/95

📌 Function<T, R>이란?

Function<T, R>은 입력값 T를 받아 결과값 R을 반환하는 함수형 인터페이스다.

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}

즉, apply() 메서드 하나만 구현하면 되고, 람다식으로 쉽게 표현할 수 있다.

✅ 기본 사용법

import java.util.function.Function;

public class FunctionExample {
    public static void main(String[] args) {
        Function<String, Integer> stringLength = str -> str.length();

        System.out.println(stringLength.apply("Hello")); // 5
    }
}

위 예제에서는 String을 입력받아 Integer 길이를 반환하는 함수다.

🛠 주요 메서드

1. apply(T t)

입력값을 받아 결과를 반환합니다. 가장 기본적인 메서드다.

2. andThen(Function<? super R, ? extends V> after)

앞선 Function을 수행한 후에, 다음 Function을 이어서 실행한다.

Function<String, Integer> strLength = s -> s.length();
Function<Integer, String> toMessage = len -> "길이: " + len;

Function<String, String> combined = strLength.andThen(toMessage);
System.out.println(combined.apply("안녕하세요")); // "길이: 5"

3. compose(Function<? super V, ? extends T> before)

apply() 전에 먼저 실행할 함수를 정의한다. andThen과 순서가 반대다.

Function<Integer, Integer> multiply2 = x -> x * 2;
Function<String, Integer> parseAndMultiply = multiply2.compose(Integer::parseInt);

System.out.println(parseAndMultiply.apply("3")); // 6

🌍 실전 예제: 리스트에 Function 적용하기

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FunctionMapExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Apple", "Banana", "Cherry");

        Function<String, Integer> getLength = String::length;

        List<Integer> lengths = names.stream()
                                     .map(getLength)
                                     .collect(Collectors.toList());

        System.out.println(lengths); // [5, 6, 6]
    }
}

Stream의 map()은 내부적으로 Function을 사용해 각 요소를 변환한다.

🧩 Function vs Predicate vs Consumer 차이점

인터페이스입력출력목적
Function<T, R>OO값을 변환
Predicate<T>Oboolean조건 검사
Consumer<T>OX소비, 실행만 하고 반환 없음

✨ 마무리

Function<T, R>은 자바에서 데이터 변환 및 매핑에 매우 유용한 도구다.
특히 스트림과 함께 사용할 때 진가를 발휘한다. compose()와 andThen()을 활용하면 함수형 체인도 손쉽게 구성할 수 있다.

profile
앱 개발 공부 중

0개의 댓글