[JAVA8] 함수형 인터페이스

조성권·2021년 12월 5일
0
post-thumbnail

오늘은 JAVA8부터 지원하는 특징 중 하나인 함수형 인터페이스에 대해 이야기 해보고자 한다.

1. 함수형 인터페이스란?

  • 추상 메소드를 단 하나만 가지고 있는 인터페이스
  • @FunctionalInterface 어노테이션을 갖는 인터페이스

여기서 추상 메소드를 단 하나만 가지고 있는 인터페이스라는 의미는 static 메소드default 메소드는 몇개가 정의되어 있든 상관 없다는 의미이다.

@FunctionalInterface
public interface FuncInterface{
	void getInfo();	// 추상 메소드
    
	default void getData(){	// defualt Method
 		System.out.println("get Data");
	}
	staic void getStaticData(){	// static Method
		System.out.println("get Data");
	}
}

위와 같이 코드가 기입되어 있다면 이는 함수형 인터페이스에 위배되지 않는다.
@FunctionalInterface 어노테이션을 기입해주면 이를 위배하는지 여부를 컴파일 단계에서 확인해준다.

함수형 인터페이스의 추상메소드를 사용할 때는 람다표현식을 통해 간단히 표현할 수 있다.

public class FuncClass{

// body가 1줄일 경우 
FuncInterface funcInterface = () -> System.out.println("funcInterface's getInfo() called");

// body가 2줄 이상일 경우
FuncInterface funcInter = () -> {
					...
					...
				};

위 코드는 param이 없는 경우이며 param, return type이 필요한 경우라면 다음과 같이 사용 가능하다.

@FunctionalInterface
public interface FuncInterface{
	int getSum(int num);
	...
}

public class FuncClass{
FunctionalInterface funcInterface = (number) -> {return number + 10;};

System.out.println(funcInterface.getSum(1));	// 11

JAVA 기본 제공 함수형 인터페이스

  • Function<T,R>
  • BiFunction<T,U,R>
  • Consumer<T>
  • Supplier<T>
  • Predicate<T>

* Function<T,R>

T: param type
R: return type
-> T type의 param을 받아 body 로직을 실행 후, R type으로 반환한다.
실행함수: apply(T t);

Function<Integer,Integer> func = (num) -> num + 10;
System.out.println(func.apply(2));	// 12

Function<T,R>을 실제 실행하기 위해선 apply(param)을 호출해야 동작하는 것을 확인 할 수 있다.

* BiFunction<T,U,R>

T: param1 type
U: param2 type
R: result type
-> T type, U type의 param을 받아 body 로직 실행 후, R type으로 반환한다.
실행함수: apply(T t, U u);

BiFunction<String,String> bifunc = (str1, str2) -> str1+str2;

System.out.println(biFunc.apply("hello","world"));	// helloworld

* Consumer

  • T: param type
    -> T type의 param을 받아 return 없이 결과를 출력한다.
    실행함수: accept(T t);
Consumer<String> consum = (str1) ->System.out.println(str1);

consum.accept("hello");	// hello 출력

* Supplier<T>

  • T: return type
    -> param 없이 body 로직을 실행한 후, T type의 값을 return 한다.
    실행함수: get();
Supplier<String> sup = () -> {return "Hello World";};
sup.get();	// hello world 출력

* predicate<T>

  • T: param
    -> T type의 값을 받아 body 로직 수행 후, boolean 형태 값 return
    실행함수: test(T t);
Predicate<Integer> pred = (num) ->{return num == 10;};
boolean isTrue = pred.test(10); // return true
profile
천천히, 완벽히 배워나가고자 하는 웹 서비스 엔지니어

0개의 댓글