JAVA/Functional Interface

[Java] Functional Interface > Function

앵낄낄 2023. 8. 3. 23:04
반응형

git

https://github.com/ymwoo88/stream/tree/feature/function-%EC%98%88%EC%A0%9C

설명

Function 인터페이스는 apply 메서드 하나를 추상 메서드로 제공합니다.
그외 옵셔널로 compose와 andThen 디포트 메소드가 존재하고
identity 메소드의 경우 스트림에서 Collectors 사용 시 객체를 그대로 결과 값을 사용하 때 이용되는 기능입니다.

이번 글에서는 기본적인 apply 메소드에 대해서 알아보겠습니다.
(compose와 andThen의 경우 추후 별도의 글로 설명을 드려보겠습니다.)

Function

@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;
    }
}

예제

  • 예졔1) apply() 기능 사용
    • Adder라는 클래스는 Function<Integer, Integer>를 implements하였습니다.
    • 그래서 Adder 내에를 Function의 구현체로써 apply메소드를 @Override되었습니다.
    • apply내부에는 Integer타입의 param값을 받고, 결과로 Integer타입을 반환합니다.
      (요건 왜 그런지 모르시겠다면.. 제네릭 지식을 쌓고오시면 좋을 듯 합니다.
    • case1() 테스트코드에서 Adder를 인스턴스화한 후 parma값 5를 넘기면서 apply 메소드를 호출하였습니다.
    • 그 결과로 apply내 x + 10의 결과가 수행되어 15를 반환하였습니다.
    • log에서 result 값에는 최종 15의 값이 찍히게됩니다.
@Slf4j
public class FunctionTest {

    @Test
    void case1() {
        Function<Integer, Integer> myAdder = new Adder();
        int result = myAdder.apply(5);
        log.info("result : {}", result);
    }

    public static class Adder implements Function<Integer, Integer> {
        @Override
        public Integer apply(Integer integer) {
            return integer + 10;
        }
    }
}
22:49:18.889 [Test worker] INFO com.ymwoo.stream.function.FunctionTest -- result : 15

참조

https://backtony.github.io/java/2022-02-05-java-45/#fuction

반응형