본문 바로가기

Spring & Java

Java 8 - Functional interface 사용방법

반응형




public class CommonFunc {
    // 내부 구현이 정해지지 않은 인터페이스 함수를 선언
@FunctionalInterface
public interface intFunc {
public int calc(int a, int b);
}

@FunctionalInterface
public interface strFunc {
public String strAppender(String s1, String s2);
}
}

@Test
public void test1(){
    // 하나의 변수에 하나의 함수를 매핑 하는 람다식

// 인터페이스를 실제로 어떻게 사용할지를 아래 람다식으로 구현 하도록 한다.


CommonFunc.intFunc add = (int a, int b) -> a+b;

int result = add.calc(1,2);
System.out.println(result);

CommonFunc.strFunc strAppend = (String ss1, String ss2) -> ss1 + ss2;
String result1 = strAppend.strAppender("hello","world");
System.out.println(result1);
}

공통으로 사용할 즉 내부 로직은 다르고 입력갑과 결과 값이 다를 경우 사용하면 좋을것 같다.




반응형