Function

Function (함수형 인터페이스)

하나의 인자를 받아 결과를 생성하는 함수를 나타내는 함수형 인터페이스예요. java.util.function 패키지의 핵심 함수형 인터페이스 가운데 하나예요.

출처: Java API Reference

본문

Function<T,R>의 추상 메서드는 apply(T)로 하나의 인자를 받아 결과 R을 반환해요. 기본 메서드로 andThen(Function), compose(Function)가 있고, 정적 메서드 identity()가 있어요.

@FunctionalInterface
public interface Function<T,R>
Function<String, Integer> length = s -> s.length();
Function<Integer, String> doubled = n -> "값: " + (n * 2);

int len = length.apply("hello");  // 5
String d = length.andThen(doubled).apply("abc"); // "값: 6"

Stream.map에 가장 많이 사용돼요.

List<Integer> lengths = names.stream()
    .map(String::length)
    .toList();

Function.identity()는 입력을 그대로 반환하는 함수예요.

Function<String, String> id = Function.identity();
String same = id.apply("x"); // "x"

함수형 메서드는 apply(Object)예요. 코드와 시그니처는 원문 그대로 보존돼요.

더 알아보기