[신세계I&C KDT][Java 프로그래밍] #14 함수형 인터페이스 (0326)

박현아·2024년 3월 27일
0

신세계아이앤씨 KDT

목록 보기
14/56

3. 표준 API 함수형 인터페이스

1) 개념

: 메서드가 파라미터 및 리턴값의 존재여부에 따른 4가지 형태가 존재한다

2) java.util.function 패키지

: @FunctionalInterface 지정. 따라서 추상 메서드는 반드시 한 개 존재

(1) Consumer

  • 추상메서드가 파라미터 O, 리턴값 X
  • void accept(T t)
  • BiConsumer<T,​U>: void accept​(T t, U u)
    DoubleConsumer : void accept​(double value)
    IntConsumer: void accept​(int value)
    LongConsumer : void accept​(long value)
    ObjDoubleConsumer: void accept​(T t, double value)
    ObjIntConsumer : void accept​(T t, int value)
    ObjLongConsumer: void accept​(T t, long value)

(2) Supplier

  • 추상메서드가 파라미터 X 리턴값은 O
  • T get()
  • BooleanSupplier: boolean getAsBoolean()
    DoubleSupplier: double getAsDouble()
    IntSupplier : int getAsInt()
    LongSupplier : long getAsLong()

(3) Function<T, R>

  • 추상메서드가 파라미터 O 리턴값도 O
  • R apply(T t)
  • BiFunction<T,​U,​R> : R apply​(T t, U u)
    DoubleFunction : R apply​(double value)
    DoubleToIntFunction: int applyAsInt​(double value)
    DoubleToLongFunction : long applyAsLong​(double value)
    IntFunction : R apply​(int value)
    IntToDoubleFunction : double applyAsDouble​(int value)
    IntToLongFunction: long applyAsLong​(int value)
    LongFunction: R apply​(long value)
    LongToDoubleFunction : double applyAsDouble​(long value)
    LongToIntFunction : int applyAsInt​(long value)
    ToDoubleBiFunction<T,​U>: double applyAsDouble​(T t, U u)
    ToIntFunction : int applyAsInt​(T value)

(4) Operator

  • Function 처럼 파라미터 O 리턴값도 O
  • Function API를 상속 받음
  • 전달되는 파라미터 타입과 리턴되는 타입이 똑같다
  • T apply(T t1, T t2)
  • BinaryOperator : BiFunction의 하위 인터페이스
    DoubleBinaryOperator: double applyAsDouble​(double left, double right)
    DoubleUnaryOperator: double applyAsDouble​(double operand)
    IntBinaryOperator : int applyAsInt​(int left, int right)
    IntUnaryOperator : int applyAsInt​(int operand)
    LongBinaryOperator: long applyAsLong​(long left, long right)
    LongUnaryOperator : long applyAsLong​(long operand)
    UnaryOperator: T apply(T t)

(5) Predicate

  • 추상메서드가 파라미터 O 리턴값도 O
  • 리턴값은 boolean으로 제한됨
  • 조건 체크하는 용도
  • 논리연산자 역할의 메서드 제공
    && and()
    || or()
    ! negate()
  • boolean test (T t)
  • BiPredicate<T,​U> : boolean test​(T t, U u)
    DoublePredicate : boolean test​(double value)
    IntPredicate : boolean test​(int value)
    LongPredicate : boolean test​(long value)

(3) Consumer, Function 같은 인터페이스는 여러 개 인터페이스를 순차적으로 설정

  • andThen()
>
// 1. Consumer 순차적 작업
Consumer<String> c = t-> System.out.println("람다 Consumer1: " + t);
Consumer<String> c2 = t-> System.out.println("람다 Consumer2: " + t);
	
Consumer<String> c3 = c.andThen(c2);
c3.accept("hello");
	
// 2. Function 순차적 작업
Function<String, Integer> f =  t->t.length();
Function<Integer, Float> f2 =  t->t + 3.14F;
	
Function<String, Float> f3 =    f.andThen(f2);
System.out.println(f3.apply("hello"));

0개의 댓글