Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

함수형 인터페이스 본문

Java/JAVA3

함수형 인터페이스

빌드이너프 2023. 8. 9. 23:41

함수형 인터페이스

단 하나의 추상 메서드만 선언된 인터페이스

@FunctionalInterface // 안붙여도 에러는 발생하지 않는다
interface MyFunction {
    public abstract int max(int a, int b);
}

MyFunction f = new MyFunction() {
    public int max(int a, int b) {
        return a > b ? a : b;
    }
}

 

int value = f.max(3, 5); // OK, MyFunction에 max()가 있음

 

함수형 인터페이스 타입의 참조변수로 람다식을 참조할 수 있음

(단, 함수형 인터페이스의 메서드와 람다식의 매개변수 개수와 반환타입이 일치해야함)

MyFunction f = (a, b) -> a > b ? a : b;
int value = f.max(3,5); // 실제로는 람다식(익명 함수)이 호출됨

 

코드

class lambdaTest {
    public static void main(String[] args) {
        // Object obj = (a, b) -> a > b ? a : b // 람다식, 익명객체
        MyFunction f = new MyFunction() {
            public int max(int a, int b) { // 오버라이딩: 접근제어자는 좁게 못바꾼다(public)
                return a > b ? a : b;
            }
        };

        int value = f.max(3, 5); // 함수형 인터페이스
        System.out.println("value="+value);

    }
}

@FunctionalInterface
interface MyFunction {
    int max(int a, int b);
}


value = 5

 

매개변수 타입과 결과 타입이 같아야 한다(a와 b말고 c가 들어가면 오류 남)

class lambdaTest {
    public static void main(String[] args) {
        // Object obj = (a, b) -> a > b ? a : b // 람다식, 익명객체
//        MyFunction f = new MyFunction() {
//            public int max(int a, int b) { // 오버라이딩: 접근제어자는 좁게 못바꾼다(public)
//                return a > b ? a : b;
//            }
//        };


        // 람다식(익명 객체)을 다루기 위한 참조변수의 타입은 함수형 인터페이스로 한다
        MyFunction f = (a, b) -> a > b ? a : b; // 람다식, 익명객체

        int value = f.max(3, 5); // 함수형 인터페이스
        System.out.println("value="+value);

    }
}

@FunctionalInterface
interface MyFunction {
    int max(int a, int b);
}


value = 5

 

 

익명 객체를 람다식으로 대체

List<String> list = Arrays.asList("abc", "aaa", "bbb", "ddd", "aaa");

Collections.sort(list, new Comparator<String>() {
    public int compare(String s1, String s2) {
        return s2.compareTo(s1);
    {
});

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

 

대체

List<String> list = Arrays.asList("abc", "aaa", "bbb", "ddd", "aaa");

Collections.sort(list, (s1, s2)-> s2.compareTo(s1));

 

함수형 인터페이스 타입의 매개변수, 반환타입

함수형 인터페이스 타입의 매개변수

@FunctionalInterface
interface MyFunction {
    void myMethod();
}

void aMethod(MyFunction f) {
    f.myMethod(); // MyFunction에 정의된 메서드 호출
}

 

aMethod를 호출하는 코드

MyFunction f = () -> System.out.println("myMethod()");
aMethod(f);

// 두 문장을 하나로 합치기
aMethod(() -> System.out.println("myMethod()"));

 

함수형 인터페이스 타입의 반환타입

MyFunction myMethod() {
    MyFunction f = () -> {};
    return f;
}

 

줄이면

MyFunction myMethod() {
    return () -> {};
}

 

 

코드

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

class FunctionalInterfaceTest {
    static void execute(MyFunction f) { // 매개변수의 타입이 MyFunction인 메서드
        f.run();
    }

    static MyFunction getMyFunction() { // 반환 타입이 MyFunction인 메서드
        MyFunction f = () -> System.out.println("f3.run()");
        return f;
    }

    public static void main(String[] args) {
        // 람다식으로 MyFunction의 run()을 구현
        MyFunction f1 = ()-> System.out.println("f1.run()");

        MyFunction f2 = new MyFunction() {  // 익명클래스로 run()을 구현
            public void run() {   // public을 반드시 붙여야 함
                System.out.println("f2.run()");
            }
        };

        MyFunction f3 = getMyFunction();

        f1.run();
        f2.run();
        f3.run();

        execute(f1);
        execute( ()-> System.out.println("run()") );
    }
}


f1.run()
f2.run()
f3.run()
f1.run()
run()

'Java > JAVA3' 카테고리의 다른 글

java.util.function 패키지  (0) 2023.08.10
람다식(Lambda Expression)  (0) 2023.08.09
wait()와 notify()  (0) 2023.08.08
쓰레드의 동기화(synchronization)  (0) 2023.08.07
join(), yield()  (0) 2023.08.07