Functional Interface

Ahri·2021년 12월 5일
1

JAVA

목록 보기
1/6

인프런의 더자바, JAVA8 강의를 들으며 정리한 내용입니다.

함수형 인터페이스란?

  • 추상 메소드를 딱 하나만 가지고 있는 인터페이스 (SAM, Single Abstract Method)
//A_FunctionalInterface.java
public interface A_FunctionalInterface {
    void doIt(); // abstract
}

//Main.java
A_FunctionalInterface functionalInterface = () -> {
	System.out.println("hello");
};
functionalInterface.doIt(); //hello

자바에서 미리 정의한 함수 인터페이스

  • 함수를 First class object (일급객체) 로 사용할 수 있음
    - 사용할 때 다른 요소들과 아무런 차별이 없다는 뜻
    - 다른 객체들에 일반적으로 적용가능한 연산을 모두 지원하는 객체
  • 순수 함수 (Pure function)
    - 사이드 이팩트가 없음. 입력값이 동일하면 결과값이 동일
    - 상태가 없음 (함수 밖에 있는 값을 사용하지 않는다.)
  • 고차 함수 (Higher-Order Function)
    - 함수가 함수를 매개변수로 받을 수 있고 함수를 리턴할 수도 있음
  • 불변성(변하지 않음)

1. Function

T 타입을 받아서 R 타입을 리턴. R apply(T t). andThen, compose

Function<Integer,Integer> plus10 = (i) -> i+10;
Function<Integer,Integer> multiply2 = (i) -> i*2;

//compose 는 괄호 안 부터 실행 : multiply2 -> plus10 
System.out.println(plus10.compose(multiply2).apply(1)); //1*2+10 = 12
//andThen 는 괄호를 나중에 실행 : plus10 -> multiply2 
System.out.println(plus10.andThen(multiply2).apply(1)); //(1+10)*2 = 22

2. BiFunction<T, U, R>

두 개의 값(T, U)를 받아서 R 타입을 리턴. R apply(T t, U u)

BiFunction<Integer,Integer,Integer> multiply = (i,j) -> i*j;

System.out.println(multiply.apply(10,5)); // 50

3. Consumer< T >

T 타입을 받아서 아무값도 리턴하지 않는 함수. void Accept(T t). andThen

Consumer<Integer> printT = System.out::println; 
		// (i) -> System.out.println(i);
printT.accept(10); // 10

4. Supplier< T >

T 타입의 값을 제공. T get()

Supplier<Integer> ten = () -> 10;
  
System.out.println(ten.get()); //10

5. Predicate< T >

T 타입을 받아서 boolean을 리턴. boolean test(T t). And, Or, Negate

Predicate<String> startsWithAhri = (s) -> s.startsWith("ahri");

System.out.println(startsWithAhri.test("ahriNara")); //true

0개의 댓글