[Java 8] 7. Method Reference

seony·2023년 4월 24일

java8

목록 보기
7/16

Method Reference란?

  • Java8에 추가된 내용으로 Functional Interface 구현을 간편하게 하기 위한 목적이다.
  • Lambda 표현식에서 더 줄여서 사용할 수 있다.
  • 클래스에 있는 메서드를 참조하는 것이다!

Method Reference 형식

  • ClassName::instance-methodName
  • ClassName::static-methodName
  • Instance::methodName

언제 사용할까?

  • 람다를 사용할 경우
    • Function<String, String> toUpperCaseLambda = (s) -> s.toUpperCase();
  • Method Reference를 사용할 경우
    • Function<String, String> toUpperCaseMethodReference = String::toUpperCase;

사용 못하는 경우

  • Predicate<Student> predicateUsingLambda = (s) -> s.getGradeLevel() >= 3;
  • 이처럼 직접 코드를 구현한 경우 메서드를 참조하는 형태가 아니기 때문에 사용하지 못한다.

Function Method Reference 예시

package com.learnJava.methodreference;

import java.util.function.Function;

public class FunctionMethodReferenceExample {

	/**
     * 람다를 사용한 경우
     */
    static Function<String, String> toUpperCaseLambda = (s) -> s.toUpperCase();

	/**
     * Method Reference를 사용한 경우
     */
    static Function<String, String> toUpperCaseMethodReference = String::toUpperCase;

    public static void main(String[] args) {
        System.out.println(toUpperCaseLambda.apply("java8"));
        System.out.println(toUpperCaseMethodReference.apply("java8"));
    }
}

Consumer MethodReference 예시

package com.learnJava.methodreference;

import com.learnJava.data.Student;
import com.learnJava.data.StudentDataBase;

import java.util.function.Consumer;

public class ConsumerMethodReferenceExample {

    /**
     * classname::methodName
     */
    static Consumer<Student> c1 = System.out::println;


    /**
     * classname::instanceMethodName
     */
    static Consumer<Student> c2 = Student::printListOfActivities;


    public static void main(String[] args) {
        StudentDataBase.getAllStudents().forEach(c1);
        System.out.println("========================================");
        StudentDataBase.getAllStudents().forEach(c2);
    }
}

0개의 댓글