자바/개념

[Java] 함수형 인터페이스(Functional Interface) 란?

대전집주인 2024. 4. 11. 17:40
728x90
SMALL

1) 개념

함수형 인터페이스란 1 개의 추상 메소드를 갖는 인터페이스를 말한다.


Java8 부터 인터페이스는 기본 구현체를 포함한 디폴트 메서드 (default method) , 정적 메서드(Static method) 를 포함할 수 있으며 여러 개의 디폴트 메서드가 있더라도 추상 메서드가 오직 하나라면 함수형 인터페이스다.

자바의 람다 표현식은 함수형 인터페이스로만 사용 가능하다.

 

2) 함수형 인터페이스 만들기

@FunctionalInterface
public interface functionalTest {
    void test();

    static void firstTest(){
        System.out.println("firstTest");
    }
    
    default void secondTest(){
        System.out.println("secondTest");
    }
}

 

위 코드를 보면 test() 메서드를 제외하고 firstTest(), secondTest() 메서드가 둘다 존재하는데 이것은 함수형 인터페이스가 아닐까?

 

위에서 말했듣이 추상 메서드는 한개만 존재하고 나머지 디폴트 메서드, 정적 메서드가 여러개라면 이것은 함수형 인터페이스가 맞다.

 

@FunctionalInterface 어노테이션을 붙어주면 위와 같은 규칙을 지키지 않으면 컴파일시 에러가 발생하여 규칙을 위반하는걸 방지할 수 있다.

Invalid '@FunctionalInterface' annotation; functionalTest is not a functional interface

 

3) 함수형 인터페이스 제너릭으로 정의 가능

참조 : https://zzang9ha.tistory.com/303

 

4) 자바에서 기본적으로 제공하는 함수형 인터페이스

Predicate

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}

Predicate 는 인자 하나를 받아서 boolean 타입을 리턴한다.
람다식으로는 T -> boolean 로 표현

 

Consumer

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

Consumer 는 인자 하나를 받고 아무것도 리턴하지 않는다.
람다식으로는 T -> void 로 표현

 

Supplier

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

Supplier 는 아무런 인자를 받지 않고 T 타입의 객체를 리턴한다.
람다식으로는 () -> T 로 표현

 

Function

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

Function 은 T 타입 인자를 받아서 R 타입을 리턴한다.
람다식으로는 T -> R 로 표현
T 와 R 은 같은 타입을 사용할 수도 있다.

 

Comparator

@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
}

Comparator 은 T 타입 인자 두개를 비교하여 int 타입을 리턴한다.
람다식으로는 (T, T) -> int 로 표현

 

Runnable

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

Runnable 은 아무런 객체를 받지 않고 리턴도 하지 않고 실행만 해준다.
람다식으로는 () -> void 로 표현

 

Callable

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}

Callable 은 아무런 인자를 받지 않고 T 타입 객체를 리턴한다.
람다식으로는 () -> T 로 표현

 

Reference : https://bcp0109.tistory.com/313?

 

Java 8 함수형 인터페이스 (Functional Interface)

Overview 함수형 인터페이스란 1 개의 추상 메소드를 갖는 인터페이스를 말합니다. Java8 부터 인터페이스는 기본 구현체를 포함한 디폴트 메서드 (default method) 를 포함할 수 있습니다. 여러 개의 디

bcp0109.tistory.com

728x90
LIST