함수형 인터페이스

강9·2023년 12월 18일
0

Java

목록 보기
70/71

💡 함수형 인터페이스란?

단일 추상 메서드 인터페이스(SAM)

  • 단 하나의 추상메서드를 가진 인터페이스를 의미한다.
  • 함수형 인터페이스를 사용하면 람다 표현식을 활용할 수 있게 된다.
  • 함수형 인터페이스는 @FunctionalInterface 어노테이션을 사용하여 표시할 수 있다.
  • 어노테이션은 선택 사항이지만 컴파일러에게 해당 인터페이스가 함수형 인터페이스라는 것을 알려주는 역할을 한다.

@FunctionalInterface
interface MathOperation {
int operation(int x, int y);
}

💡 함수형 인터페이스 메서드 참조

이미 정의된 메서드를 직접 참조하여 람다 표현식을 더욱 간결하게 만들 수 있다.

  • 메서드 참조는 기존 메서드를 재사용하고 코드 중복을 줄이는데 도움이 된다.
  • 메서드 참조는 다음 네가지 유형이 있다.
    1) 정적 메소드 참조 : 클래스명::메서드명
    2) 인스턴스 메서드 참조 : 객체참조::메서드명
    3) 특정 객체의 인스턴스 메서드 참조 : 클래스명::메서드명
    4) 생성자 참조 : 클래스명::new

📌 함수형 인터페이스(@FunctionalInterface)

@FunctionalInterface
public interface Converter<F,T> {
	T convert(F from);
}

1️⃣ 정적 메서드 참조 : 클래스명::메서드명

import ...Converter;

public class IntegerUtils {

    public static int stringToInt(String s) {
        return Integer.parseInt(s);
    }

    public static void main(String[] args) {
//  정적 메서드 참조 : 클래스::메서드명
        Converter<String, Integer> converter = IntegerUtils::stringToInt;
        Integer result = converter.converter("123");
        System.out.println(result); // "123" --> 123
    }
}

2️⃣ 인스턴스 메서드 참조 : 객체참조::메서드명

import ...Converter;

public class StringUtils {

    public String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }

    public static void main(String[] args) {
//  인스턴스 메서드 참조 : 객체참조::메서드명
        StringUtils stringUtils = new StringUtils();
        Converter<String, String> converter = stringUtils::reverse;
        String result = converter.converter("hello");
        System.out.println(result); // "hello" --> "olleh"
    }
}

3️⃣ 특정 객체의 인스턴스 메서드 참조: 클래스명::메서드명

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class test {
//  특정 객체의 인스턴스 메서드 참조 : 클래스명::메서드명
    public static void main(String[] args) {
        List<String> names = Arrays.asList("John", "Jane", "Doe");
//      String 클래스의 compareTo 메서드 참조
        Collections.sort(names, String::compareTo);
        System.out.println(names); // "John", "Jane", "Doe" --> [Doe, Jane, John]
    }
}

4️⃣ 생성자 참조

public class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        PersonFactiory personFactiory1 = Person::new;
        Person person1 = personFactiory1.create("John Doe", 30);

//      람다 표현식을 사용하는 방법
        PersonFactiory personFactiory2 = (name, age) -> new Person(name, age);
        Person person2 = personFactiory2.create("John Doe", 30);

//      익명 클래스를 사용한 예제(이전 방법 --> X)
        PersonFactiory personFactiory3 = new PersonFactiory() {
            @Override
            public Person create(String name, int age) {
                return new Person(name, age);
            }
        };
        Person person3 = personFactiory3.create("John Doe", 30);

    }
}

interface PersonFactiory {
    Person create(String name, int age);
}
profile
코린이 일기

0개의 댓글