상세 컨텐츠

본문 제목

[Function] function 자세한설명

자바

by esoesmio 2023. 4. 6. 01:47

본문

Function 인터페이스

Function Interface는 Java에서 함수형 프로그래밍을 구현하기 위해 Java 버전 1.8부터 도입된 함수형 인터페이스로 한 개의 매개변수를 전달받아 특정 작업을 수행 후 새로운 값을 반환하는 경우 사용됩니다.

 

제네릭 타입인 한 개의 인수가 존재하며, 제네릭 타입을 반환합니다.

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

  default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
    Objects.requireNonNull(before);
    return (V v) -> apply(before.apply(v));
  }

  default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
    Objects.requireNonNull(after);
    return (T t) -> after.apply(apply(t));
  }

  static <T> Function<T, T> identity() {
    return t -> t;
  }
}

Function 인터페이스는 두 개의 제네릭 타입을 사용합니다.

T: 첫 번째 매개변수의 타입입니다.

R: 반환 타입입니다.

 

인터페이스 내부에는 한 개의 추상 메서드, 두 개의 디폴트 메서드, 한 개의 정적 메서드가 존재합니다.

 

[추상 메서드 목록]

- apply() 메서드

 

[디폴트 메서드 목록]

- compose() 메서드

- andThen() 메서드

 

[정적 메서드]

- identity() 메서드

 

람다 표현식을 사용하면 추상 메서드인 apply() 메서드를 구현하기 위해 클래스를 정의할 필요가 없으며, Function 타입의 객체에 할당된 람다 표현식은 apply() 메서드를 구현하기 위해 사용됩니다.


Function 인터페이스의 apply 메서드

apply() 메서드는 제네릭 타입인 한 개의 매개변수를 전달받아 특정 작업을 수행 후 값을 반환합니다.

R apply(T t);

다음 예제는 apply() 메서드 사용 방법입니다.

 

먼저, 세 개의 Function 타입의 객체를 생성하며 특정 작업을 수행 후 값을 반환하는 람다 표현식을 할당합니다.

- functionAdd 객체는 Integer 타입의 매개변수를 전달받아 100을 더한 결과를 문자열로 반환합니다.

- functionMinus 객체는 Integer 타입의 매개변수를 전달받아 100을 뺄셈한 결과를 문자열로 반환합니다.

- functionMultiple 객체는 Integer 타입의 매개변수를 전달받아 100을 곱한 결과를 문자열로 반환합니다.

public static void main(String args[]) {
  Function<Integer, String> functionAdd =
          (num) -> Integer.toString(num + 100);

  Function<Integer, String> functionMinus =
          (num) -> Integer.toString(num - 100);

  Function<Integer, String> functionMultiple =
          (num) -> Integer.toString(num * 100);

  System.out.println("50 + 100 = " + functionAdd.apply(50));
  System.out.println("50 - 100 = " + functionMinus.apply(50));
  System.out.println("50 * 100 = " + functionMultiple.apply(50));
}

[실행 결과]

50 + 100 = 150
50 - 100 = -50
50 * 100 = 5000

Funciton 인터페이스의 compose 메서드

Function 인터페이스에는 디폴트 메서드인 compose() 메서드가 존재합니다.

default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
  Objects.requireNonNull(before);
  return (V v) -> apply(before.apply(v));
}

compose() 메서드의 매개변수는 Function 타입의 객체를 전달받습니다.

※ 주의사항
아래에서 소개할 andThen() 메서드와 달리 compose() 메서드에 람다 표현식을 전달할 수 없습니다.

compose() 메서드는 매개변수로 전달받은 Function 객체의 apply() 메서드를 호출 후 반환 결과를 apply() 메서드에 전달합니다.

 

다음 예제는 compose() 메서드 반환 결과를 apply() 메서드에 전달합니다.

public static void main(String args[]) {
  Function<Integer, Integer> functionAdd =
          (num) -> num + 100;

  Function <Integer, Integer> functionMultiple =
          (num) -> num * 10;

  System.out.println("(50 * 100) + 10 = " +
          functionAdd.compose(functionMultiple).apply(50));
}

[실행 결과]

(50 * 100) + 10 = 600

Function 인터페이스의 andThen 메서드

Function 인터페이스에는 디폴트 메서드인 andThen() 메서드가 존재합니다.

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
  Objects.requireNonNull(after);
  return (T t) -> after.apply(apply(t));
}

andThen() 메서드의 매개변수는 Function 타입의 객체를 전달받거나 한 개의 매개변수를 가지며, 반환 타입이 존재하는 람다 표현식을 전달받습니다.

 

andThen() 메서드는 apply() 메서드 호출 후 반환 결과를 매개변수로 전달받은 Function 객체의 apply() 메서드에 전달합니다.

 

다음 예제는 apply() 메서드 반환 결과를 andThen() 메서드에 전달합니다.

public static void main(String args[]) {
  Function<Integer, Integer> functionAdd =
          (num) -> num + 100;

  Function <Integer, Integer> functionMultiple =
          (num) -> num * 10;

  System.out.println("(50 + 100) * 10 = " +
          functionAdd.andThen(functionMultiple).apply(50));
}

[실행 결과]

(50 + 100) * 10 = 1500

'자바' 카테고리의 다른 글

[람다+함수형인터페이스] 카드연장  (0) 2023.04.06
[bifunction]바이펑션 인터페이스  (0) 2023.04.06
[Optional] Optional클래스  (0) 2023.04.05
[병렬스트림] 병렬에 대한 정보  (0) 2023.04.05
[Function] 사용방식  (0) 2023.04.05

관련글 더보기

댓글 영역