/ JAVAJUNGSUK

Ch14-13~14. 메서드 참조

자바의 정석 기초편

0. 목차



Chapter14. 람다와 스트림

Ch14 - 13. 메서드 참조

Ch14 - 14. 생성자의 메서드 참조



Ch14 - 13. 메서드 참조


▶ 메서드 참조(method reference)란?

▷ 하나의 메서드만 호출하는 람다식을 더 간단히 한 것
▷ 메서드 참조 생성 방법
ClassName::methodName


▶ static 메서드 참조

▷ 람다식 : (x) -> ClassName, method(x)
▷ 메서드 참조 : ClassName::method
▷ 예시
// 이 메서드가 하는 일은 Integer.parseInt(String s)만 호출
Integer method(String s) {
    return Integer.parseInt(s);
}

// method 호출
int result = obj.method("123");

// method 생성하지 않고 호출하면서 parseInt 바로 사용 가능
int result = Integer.parseInt("123");
  • 이 모든 걸 람다식으로 바꾸면??
    Function<입력, 출력> f = (입력된 내용 s) -> parseInt(s);
      Function<String, Integer> f = (String s) -> Integer.parseInt(s);
    
  • 사실 람다식도 중복되는 게 있음
    Function<String, Integer> f =(String s)-> Integer.parseInt(s);

  • 메서드 참조로 더 간략히 만들기
      Function<String, Integer> f = Integer::parseInt;
    


▶ 인스턴스 메서드 참조

▷ 람다식 : (obj, x) -> obj.method(x)
▷ 메서드 참조 : ClassName::method



Ch14 - 14. 생성자의 메서드 참조


▶ 생성자와 메서드 참조

▷ supplier : 매개변수 0개
// Supplier는 주기만 함, MyClass를 출력하는 람다식
Supplier<MyClass> s = () -> new MyClass();

// 메서드 참조로 변경
Supplier<MyClass> s = MyClass::new;
▷ Function : 매개변수 1개
// 람다식
Function<Integer, MyClass> s = (i) -> new MyClass(i);

// 메서드 참조로 변경
Function<Integer, MyClass> s = MyClass::new;


▶ 배열과 메서드 참조

▷ Function
// 람다식
Function<Integer, int[]> f = x -> new int[x]

// 메서드 참조로 변경
Function<Integer, int[]> f2 = int[]::new;


▶ 실습

▷ 입력 없이 MyClass 객체를 반환하는 람다식 생성
...
Supplier<MyClass> s = () -> new MyClass(); // 입력 없어서 Supplier 사용

MyClass mc = s.get();
System.out.println(mc);
...

class MyClass {}

// console
baek.MyClass@4141d797
▷ 람다식을 메서드 참조로 변경
...
Supplier<MyClass> s = MyClass::new;

MyClass mc = s.get();
System.out.println(mc);
...

class MyClass {}

// console
baek.MyClass@57fa26b7


▷ MyClass 생성자가 매개변수를 가짐
class MyClass {

    int iv;
    
    MyClass(int iv) {
        this.iv = iv;
    }
}


▷ Supplier를 Function으로 변경
...
Supplier<MyClass> s = MyClass::new; // 메서드 참조
Supplier<MyClass> s = () -> new MyClass(); // 람다식

// ↓↓↓↓ Function으로 변경 ↓↓↓↓
Function<Integer, MyClass> f = MyClass::new; // 메서드 참조
Function<Integer, MyClass> f = (i) -> new MyClass(i); // 람다식

MyClass mc = f.apply(100); // Function은 get이 아닌 apply 사용
System.out.println(mc.iv);
...

class MyClass {
    int iv;
    
    MyClass(int iv) {
        this.iv = iv;
    }
}

// console
100


▷ 배열 생성


...
Function<Integer, int[]> f = (i) -> new int[i]; // 람다식
Function<Integer, int[]> f = int[i]::new; // 메서드 참조

int[] mc = f.apply(100200300);
System.out.println(mc.length);
...

// console
100200300