본문 바로가기
카테고리 없음

Java 8의 Consumer, Supplier, Function, Operator, Predicate 를 알아보자.

by 트라네스 2024. 12. 23.
728x90
반응형


 예전에 Consumer, Supplier, Function, Operator, Predicate 에 대해서 공부를 하다가 정확하게 정리를 못해놔서 이 참에 정리를 하려고 한다. 개념은 다들 뭐 이런거지 하지만 백문이 불여일타에 예제를 보다보면 뭔가 좀 허하다. 그래서 추가로 정리한다.

 

인터페이스 역할 메서드
Consumer 입력을 받아 처리만 함 void accept(T t)
Supplier 값을 공급 T get()
Function 입력 → 출력 변환 R apply(T t)
Operator 입력과 출력 타입이 같음 T apply(T t)
Predicate 조건에 따라 boolean 반환 boolean test(T t)

 

1.  Consumer

설명:

  • 입력을 받아 처리하지만 결과를 반환하지 않습니다.
  • 보통 데이터를 출력하거나 로그를 남길 때 사용합니다.

메서드:

  • void accept(T t)

예제:

import java.util.function.Consumer;

public class CustomConsumer<T> implements Consumer<T> {
    @Override
    public void accept(T t) {
        System.out.println("Default Consumer: " + t);
    }

    // 오버로딩된 메서드
    public void accept(T t, String additionalInfo) {
        System.out.println("Custom Consumer: " + t + ", Info: " + additionalInfo);
    }

    public static void main(String[] args) {
        CustomConsumer<String> customConsumer = new CustomConsumer<>();
        customConsumer.accept("Hello");
        customConsumer.accept("Hello", "Extra Info");
    }
}

 

 

2. Supplier

설명:

  • 아무런 입력 없이 값을 반환합니다.
  • 주로 데이터를 생성하거나 값을 공급할 때 사용합니다.

메서드:

  • T get()

예제:

import java.util.function.Supplier;

public class CustomSupplier<T> implements Supplier<T> {
    private final T value;

    public CustomSupplier(T value) {
        this.value = value;
    }

    @Override
    public T get() {
        return value;
    }

    // 오버로딩된 메서드
    public T get(String prefix) {
        System.out.println(prefix + " returning value");
        return value;
    }

    public static void main(String[] args) {
        CustomSupplier<String> customSupplier = new CustomSupplier<>("Hello, Supplier!");
        System.out.println(customSupplier.get());
        System.out.println(customSupplier.get("CustomSupplier:"));
    }
}

 

3. Function

설명:

  • 입력을 받아 처리한 후 결과를 반환합니다.
  • 주로 데이터를 변환하거나 매핑할 때 사용됩니다.

메서드:

  • R apply(T t)

예제:

import java.util.function.Function;

public class CustomFunction<T, R> implements Function<T, R> {
    @Override
    public R apply(T t) {
        return (R) ("Default transformation of: " + t);
    }

    // 오버로딩된 메서드
    public R apply(T t, String prefix) {
        return (R) (prefix + " transformed value: " + t);
    }

    public static void main(String[] args) {
        CustomFunction<Integer, String> customFunction = new CustomFunction<>();
        System.out.println(customFunction.apply(10));
        System.out.println(customFunction.apply(10, "CustomFunction:"));
    }
}

 

4. Operator

설명:

  • Function의 변형으로, 입력과 출력의 타입이 같은 경우 사용됩니다.
  • 자주 사용되는 변형은 UnaryOperator(하나의 입력), BinaryOperator(두 개의 입력)입니다.

메서드:

  • UnaryOperator: T apply(T t)
  • BinaryOperator: T apply(T t1, T t2)

예제:

설명:

  • Function의 변형으로, 입력과 출력의 타입이 같은 경우 사용됩니다.
  • 자주 사용되는 변형은 UnaryOperator(하나의 입력), BinaryOperator(두 개의 입력)입니다.

메서드:

  • UnaryOperator: T apply(T t)
  • BinaryOperator: T apply(T t1, T t2)

예제:

import java.util.function.UnaryOperator;

public class CustomOperator implements UnaryOperator<Integer> {
    @Override
    public Integer apply(Integer x) {
        return x * x; // 기본 제곱 연산
    }

    // 오버로딩된 메서드
    public Integer apply(Integer x, Integer y) {
        return x + y; // 덧셈 연산
    }

    public static void main(String[] args) {
        CustomOperator operator = new CustomOperator();
        System.out.println(operator.apply(5)); // 출력: 25 (제곱)
        System.out.println(operator.apply(5, 10)); // 출력: 15 (덧셈)
    }
}

 

5. Predicate

설명:

  • 입력을 받아 조건에 따라 true 또는 false를 반환합니다.
  • 주로 필터링 조건을 정의할 때 사용됩니다.

메서드:

  • boolean test(T t)

예제:

import java.util.function.Predicate;

public class CustomPredicate<T> implements Predicate<T> {
    @Override
    public boolean test(T t) {
        return t != null; // 기본 조건: null이 아닌지 확인
    }

    // 오버로딩된 메서드
    public boolean test(T t, String additionalCondition) {
        return t != null && t.toString().contains(additionalCondition); // 추가 조건 확인
    }

    public static void main(String[] args) {
        CustomPredicate<String> customPredicate = new CustomPredicate<>();
        System.out.println(customPredicate.test("Hello")); // 출력: true
        System.out.println(customPredicate.test("Hello", "ell")); // 출력: true
        System.out.println(customPredicate.test("Hello", "xyz")); // 출력: false
    }
}

 

 공부를 하다보면 개념은 알겠고 저런 방식으로 쓸 때는 알겠는데, 막상 실제 주어진 Interface 를 오버로딩 혹은 오버라이딩을 해서 사용하는 케이스에 대해서 좀 더 이해가 필요할 것 같아서 예제 코드를 추가로 작성합니다.

728x90
반응형

댓글


TOP

TEL. 02.1234.5678 / 경기 성남시 분당구 판교역로