Language/JAVA

[JAVA] 표준 API 함수적 인터페이스 - 람다식 및 메서드 참조(Method Reference)

gangintheremark 2023. 9. 7. 12:43
728x90

메서드 참조 (Method Reference)

람다식을 더 간략하게 표현

  • 객체생성 Method reference
  • 인스턴스 메서드 호출 Method reference
  • static 메서드 호출 Method reference
  • System.out::printlnt Method reference

 

표준 API 함수적 인터페이스

  • Consumer : 파라미터 있고 리턴값 없는 경우
  • Supplier : 파라미터 없고 리턴값 있는 경우
  • Function : 파라미터 있고 리턴값 있는 경우
  • Operator : 파라미터 있고 리턴값 있는 경우 ➜ 파라미터와 리턴타입 동일
  • Predicate : 파라미터 있고 리턴값 있는 경우 ➜ 리턴값은 boolean

 

Consumer<T> 인터페이스

  • 파라미터 있고 리턴값 없는 경우
  • accept(T) 메서드 처리
import java.util.function.Consumer;

public class ConsumerTest {
    public static void main(String[] args) {

        //  익명클래스
        Consumer<String> c = new Consumer<String>() {
            @Override
            public void accept(String t) {
                System.out.println(t);
            }
        };
        c.accept("빵빵이");
        // 실행결과: 빵빵이
    }
}

💡 람다식

Consumer<String> c = t -> System.out.println(t);

💡 Method Reference

Consumer<String> c = System.out::println;

 

파라미터가 두 개인 경우

  • BiConsumer 인터페이스 : accept(T t, U u) 메서드 처리
BiConsumer<String, Integer> x = (t, u) -> System.out.println(t + "\t" + u);
x.accept("빵빵이", 10);

 

파라미터 타입에 따른 인터페이스

파라미터 한 개인 경우

  • IntConsumer 인터페이스: accept(int value) 메서드 처리
  • DoubleConsumer 인터페이스: accept(double value) 메서드 처리
  • LongConsumer 인터페이스: accept(long value) 메서드 처리

파라미터 두 개인 경우

  • ObjIntConsumer 인터페이스: accept(T t, int value) 메서드 처리
  • ObjDoubleConsumer 인터페이스: accept(T t, double value) 메서드 처리
  • ObjLongConsumer 인터페이스: accept(T t, long value) 메서드 처리

 

Supplier<T> 인터페이스

  • 파라미터 없고 리턴값 있는 경우
  • T get() 메서드 처리
import java.util.function.Supplier;

class Sample {
    public Sample() {
        // 생성자
    }
}

public class test {
    // Sample 클래스의 생성자를 이용한 객체 생성
    public static void main(String[] args) {

        Supplier<Sample> s = new Supplier<Sample>() {
            @Override
            public Sample get() {
                return new Sample();
            }
        };
        System.out.println(s.get());
    }
}

💡 람다식

Supplier<Sample> s = () -> new Sample();

💡 Method Reference

Supplier<Sample> s = Sample::new;

 

BooleanSupplier 인터페이스

  • boolean getAsBoolean() 메서드 처리
BooleanSupplier x = () -> {return num % 2 == 0;};

 

Function<T, R> 인터페이스

  • 파라미터 있고 리턴값 있는 경우
  • R apply(T t) 메서드 처리
import java.util.function.Function;

public class FunctionTest {
    public static void main(String[] args) {

        Function<String, Integer> f = new Function<String, Integer>() {
            @Override
            public Integer apply(String t) {
                return Integer.parseInt(t);
            }
        };
        System.out.println(f.apply("10"));
        // 실행결과: 10
    }
}

💡 람다식

Function<String, Integer> f = t -> Integer.parseInt(t);

💡 Method Reference

Function<String, Integer> f = Integer::parseInt;

 

파라미터가 두 개인 경우

  • BiFunction<T, U, R> 인터페이스: R apply(T t, U u) 메서드 처리
/* 람다식 */
BiFunction<String, Integer, String> f = (t, u) -> t.substring(0,u);
System.out.println(y.apply("HelloWorld", 5));
// 실행결과: Hello

/* Method reference: 생성자의 파라미터가 2개(int, string)인 Sample 클래스 객체 생성 */
BiFunction<Integer, String, Sample> f = Sample::new;

 

파라미터 타입에 따른 인터페이스

파라미터가 한 개인 경우

  • IntFunction<R> 인터페이스: R apply(int value) 메서드 처리
  • DoubleFunction<R> 인터페이스: R apply(double value) 메서드 처리
  • DoubleToIntFuntion 인터페이스: int applyAsInt(double value) 메서드 처리
  • IntToDoubleFunction 인터페이스: double applyAsDouble(int value) 메서드 처리

파라미터가 두 개인 경우

  • ToIntBiFuction<T, U> 인터페이스:int applyAsInt(T t, U u)` 메서드 처리
  • ToDoubleBiFunction<T, U> 인터페이스:double applyAsDouble(T t, U u)` 메서드 처리

 

Operator 인터페이스

  • 파라미터 있고 리턴값 있는 경우
  • UnaryOperator<T> ➜ 파라미터 타입은 T, 리턴타입도 T
    • T apply(T t) 메서드 처리
import java.util.function.UnaryOperator;

public class OperatorTest {
    public static void main(String[] args) {
        /* String 클래스의 인스턴스 메서드를 사용하는 경우 */
        UnaryOperator<String> u = new UnaryOperator<String>() {
            @Override
            public String apply(String t) {
                return t.toUpperCase();
            }
        };
        System.out.println(y.apply("hello"));
        // 실행결과: HELLO
    }
}

💡 람다식

UnaryOperator<String> u = t -> t.toUpperCase();

💡 Method reference

UnaryOperator<String> u = String::toUpperCase;

 

파라미터가 두 개인 경우

  • BinaryOperator<T> 인터페이스: T apply(T t, T t2) 메서드 처리
BinaryOperator<Integer> x = (t, u) -> {return t+u;};
System.out.println(x.apply(200, 300));
// 실행결과: 500

 

파라미터 타입에 따른 인터페이스

  • DoubleUnaryOperator ➜ 파라미터 타입은 double, 리턴타입도 double
    • double applyAsDouble(double operand) 메서드 처리
  • IntUnaryOperator ➜ 파라미터 타입은 int, 리턴타입도 int
    • int applyAsInt(int operand) 메서드 처리
  • IntBinaryOperator 인터페이스 : int applyAsInt(int value, int value2) 메서드 처리

 

Predicate 인터페이스

  • 파라미터 있고 리턴값 있는 경우
  • 무조건 리턴값은 boolean이다.
  • Predicate<T> 인터페이스 : boolean test(T t)메서드 처리
import java.util.function.Predicate;

public class PredicateTest {
    public static void main(String[] args) {

        Predicate<String> p = new Predicate<String>() {

            @Override
            public boolean test(String t) {
                return t.length() == 5;
            }
        };
        System.out.println(p.test("hello"));
        // 실행결과: true
    }
}

💡 람다식

Predicate<String> p = t -> { return t.length()==5; };

 

파라미터가 두 개인 경우

  • BiPredicate<T,U> 인터페이스: boolean test(T t, U u)
BiPredicate<String, Integer> p = (t, u) -> { return t.length() == u; };

 

파라미터 타입에 따른 인터페이스

  • IntPredicate 인터페이스: boolean test(int value)
  • DoublePredicate: boolean test(double value)
728x90