java/study

[java] Function에 대해서 알아보자

얼킴 2023. 2. 24. 18:57

자바에서 Function은 함수형 프로그래밍을 지원하는 인터페이스입니다. Function 인터페이스는 하나의 인자를 받아들이고, 하나의 값을 반환합니다. 이번 포스트에서는 자바 Function 인터페이스에 대해 자세히 살펴보겠습니다.

 

Function 인터페이스

Function 인터페이스는 다음과 같이 정의됩니다.

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

Function 인터페이스는 제네릭 인터페이스로, T는 입력값의 타입, R은 반환값의 타입을 나타냅니다. apply 메서드는 Function 인터페이스의 인자를 받아들이고 반환값을 생성합니다.

 

Function 사용 예시

문자열을 대문자로 변환

Function<String, String> toUpperCase = (str) -> str.toUpperCase();
String result = toUpperCase.apply("hello, world");
System.out.println(result); // "HELLO, WORLD"

위 코드에서는 Function 인터페이스를 구현하는 람다 표현식을 toUpperCase 변수에 할당하고, apply 메서드를 호출하여 입력값을 대문자로 변환한 결과를 출력하고 있습니다.

문자열을 정수로 변환

Function<String, Integer> toInteger = (str) -> Integer.parseInt(str);
int result = toInteger.apply("123");
System.out.println(result); // 123

 

여러 개의 Function 조합

Function 인터페이스는 여러 개를 조합하여 더 복잡한 데이터 변환을 할 수 있습니다. 예를 들어, 문자열을 대문자로 변환한 후, 문자열의 길이를 구하는 코드는 다음과 같이 작성할 수 있습니다.

Function<String, String> toUpperCase = (str) -> str.toUpperCase();
Function<String, Integer> length = (str) -> str.length();
Function<String, Integer> toUpperCaseAndLength = toUpperCase.andThen(length);

int result = toUpperCaseAndLength.apply("hello, world");
System.out.println(result); // 12

위 코드에서는 toUpperCase와 length 두 개의 Function을 조합하여 toUpperCaseAndLength 변수에 할당하고 있습니다. toUpperCaseAndLength.apply("hello, world") 코드에서는 문자열을 대문자로 변환한 후, 해당 문자열의 길이를 반환하게 됩니다.

 

함수형 인터페이스 패키지

자바에서 제공하는 Function 인터페이스는 java.util.function 패키지에 위치하며, 다양한 함수형 인터페이스들이 포함되어 있습니다. Function 인터페이스 외에도 Supplier, Consumer, Predicate 등 다양한 함수형 인터페이스를 사용하여 함수형 프로그래밍을 구현할 수 있습니다.

 

마무리

이번 포스트에서는 자바 Function 인터페이스에 대해 알아보았습니다. Function 인터페이스는 자바에서 함수형 프로그래밍을 구현하는 데 매우 유용한 인터페이스입니다. 다양한 함수형 인터페이스를 활용하여 간결하고 효율적인 코드를 작성할 수 있습니다.