람다식 메소드 참조


메소드를 참조해서 매개 변수의 정보 및 리턴 타입을 알아내어,

람다식에서 불필요한 매개변수는 제거하는 것



사용법 예시)

두수를 입력받아 큰 값을 리턴하는 Math 클래스의 max메소드


1
2
3
4
5
6
7
8
//Math클래스의 max() 참조 방법
 
//람다식은 단순히 두 개의 값을 max메소드에 전달하는 역활만 함.
(x, y) -> Math.max(x, y)
 
 
//메소드 참조를 이용한 람다식 표현
Math :: max
cs



예제코드


1
2
3
4
5
6
7
8
9
10
11
12
public class Calculator {
    //정적 메소드
    public static int staticMethod(int x, int y) {
        return x + y;
    }
 
    //인스턴스 메소드    
    public int instanceMethod(int x, int y) {
        return x + y;
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MethodReferencesExample {
    public static void main(String[] args) {
        IntBinaryOperator operator;
        
        //정적 메소드 참조
        operator = (x,y) -> Calculator.staticMethod(x, y);
        System.out.println("결과 1 : " + operator.applyAsInt(1,2));
        
        operator = Calculator :: staticMethod;
        System.out.println("결과 2 : " + operator.applyAsInt(3,4));
 
        //정적 메서드는 '클래스명 :: 정적메서드' 형태로 참조 가능
        
        //인스턴스 메서드 참조
        Calculator obj = new Calculator();
        operator = (x,y) -> obj.instanceMethod(x, y);
        System.out.println("결과 3 : " + operator.applyAsInt(5,6));
        
        operator = obj :: instanceMethod;
        System.out.println("결과 3 : " + operator.applyAsInt(7,8));
    }
}
cs




람다식 생성자 참조


생성자 참조도 같은 방법으로 가능하다.



예제코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.function.BiFunction;
import java.util.function.Function;
 
public class ConstructorReferenceExample {
    
    /*
     * 람다식에서의 생성자 참조 "클래스명 :: new"
     */
    
    public static void main(String[] args) {
        Function<String, Member> function1 = Member :: new;
        //매개변수 1개
        Member member1 = function1.apply("dong1");
        
        BiFunction<StringString, Member> function2 = Member :: new;
        //매개변수 2개
        Member member2 = function2.apply("길동""dong1");
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Member {
    private String name;
    private String id;
    
    public Member() {
        System.out.println("기본 생성자");
    }
    
    public Member(String id) {//매개변수 1개
        System.out.println("Member(String id) 실행");
        this.id = id;
    }
    
    public Member(String name, String id) { //매개변수 2개
        System.out.println("Member(String name, String id) 실행");
        this.name = name;
        this.id = id;
    }
}
cs


+ Recent posts