본문 바로가기

하../java

ch14 함수형 인터페이스

함수형 인터페이스 - 단 하나의 추상 메소드만 선언된 인터페이스

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); //실행 가능 MyFunction에 max()가 있음.

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

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

MyFunction f = (a, b) -> a > b ? a : b;
int value = f.max(3,5) // 실제로는 람다식(익명 함수)이 호출됨
람다식(익명 객체)을 다루기 위한 참조변수의 타입은 함수형 인터페이스로 한다.
MyFunction f = (a, b) -> a > b ? a : b - 람다식 익명객체

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

@FunctionalInterface - 함수형 인터페이스는 단 하나의 추상 메소드만 가져야함.
interface MyFunction{
 int max(int a, int b);
}
출력값
5

함수형 인터페이스 - example

익명 객체를 람다식으로 대체
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);
                                         }
                                      };
 람다식으로 ==
 
 Collections.sort(list,(s1,s2)->s2.compareTo(s1));
                                                                   
 @FunctionalInterface - 함수형 인터페이스는 단 하나의 추상 메소드만 가져야함.
 interface Comparator<T>{
  int compare(T o1, T o2);
 }

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

void aMethod(MyFunction f){
 f.myMethod(); - MyFunction에 정의된 메소드 호출 (람다식 호출)
}

@@FunctionalInterface - 함수형 인터페이스는 단 하나의 추상 메소드만 가져야함.
interface MyFunction{
 void myMethod();
}
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 Ex14_1 {
	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' 카테고리의 다른 글

ch14 Predicate의 결합 CF와 함수형 인터페이스  (0) 2021.12.26
ch14 java.util.function 패키지  (0) 2021.12.25
ch14 람다식 작성하기  (0) 2021.12.25
ch13 wait()과 notify()  (0) 2021.12.25
ch13 스레드의 동기화(synchronization)  (0) 2021.12.25