백기선(인프런 강의)/더 자바, Java 8

자바에서 제공하는 함수형 인터페이스

레알윙 2020. 7. 7. 09:15
반응형

Java가 기본으로 제공하는 함수형 인터페이스

  • java.lang.funcation 패키지
  • 자바에서 미리 정의해둔 자주 사용할만한 함수 인터페이스
  • Function<T, R>
  • BiFunction<T, U, R>
  • Consumer<T>
  • Supplier<T>
  • Predicate<T>
  • UnaryOperator<T>
  • BinaryOperator<T>

 

Function<T, R>

  • T 타입을 받아서 R 타입을 리턴하는 함수 인터페이스
    • R apply(T t)
  • 함수 조합용 메소드
    • andThen
    • compose

 

BiFunction<T, U, R>

  • 두 개의 값(T, U)를 받아서 R 타입을 리턴하는 함수 인터페이스
    • R apply(T t, U u)

 

Consumer<T>

  • T 타입을 받아서 아무값도 리턴하지 않는 함수 인터페이스
    • void Accept(T t)
  • 함수 조합용 메소드
    • andThen

 

Supplier<T>

  • T 타입의 값을 제공하는 함수 인터페이스
    • T get()

 

Predicate<T>

  • T 타입을 받아서 boolean을 리턴하는 함수 인터페이스
    • boolean test(T t)
  • 함수 조합용 메소드
    • And
    • Or
    • Negate

 

UnaryOperator<T>

  • Function<T, R>의 특수한 형태로, 입력값 하나를 받아서 동일한 타입을 리턴하는 함수 인터페이스

 

BinaryOperator<T>

  • BiFunction<T, U, R>의 특수한 형태로, 동일한 타입의 입렵값 두개를 받아 리턴하는 함수 인터페이스

 

 

예제

import java.util.function.Function;

public class Plus10 implements Function<Integer, Integer> {
	@Override
	public Integer apply(Integer t) {
		return t  + 10;
	}

}

 

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class RunMain {

	public static void main(String[] args) {
		int testNum = 20;

		Plus10 plus10 = new Plus10();
		System.out.println(plus10.apply(1));

		// 람다를 사용하는 방법
//		Function<Integer, Integer> plus10Lamda = (i) -> {
//			return i + 20;
//		};
		Function<Integer, Integer> plus10Lamda = (i) -> i + 20;
		System.out.println(plus10Lamda.apply(20));

		// 함수 조합
		Function<Integer, Integer> multiply2 = (i) -> i * 2;
		System.out.println(multiply2.apply(2));

		// compose : 뒤에오는 함수를적용(multiply2) 한 후 이 값을 가지고
		// plus10의 입력값으로 사용한다.
		Function<Integer, Integer> multiply2Plus10 = plus10.compose(multiply2);
		System.out.println(multiply2Plus10.apply(10));
		System.out.println(plus10.andThen(multiply2).apply(3));

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

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

		// Predicate
		Predicate<String> startsWithJinseok = (s) -> s.startsWith("jinseok");
		System.out.println(startsWithJinseok.test("jinseok"));
		
		
	}

}

 

반응형