본문 바로가기

라이브러리 활용 - 람다식

메소드 참조

메소드 참조

  • 메소드를 참조해 매개변수의 정보 및 리턴 타입을 알아내 람다식에서 불필요한 매개변수를 제거


    출처, 이것이 자바다


정적 메소드와 인스턴스 메소드 참조

  • 정적 메소드를 참조 시 클래스 이름 뒤에 :: 기호를 붙이고 정적 메소드 이름을 기술


    출처, 이것이 자바다


  • 인스턴스 메소드일 경우에는 객체를 생성한 다음 참조 변수 뒤에 :: 기호를 붙이고 인스턴스 메소드 이름을 기술


    출처, 이것이 자바다


package ch16.sec05.exam01;

@FunctionalInterface
public interface Calcuable {
    double calc(double x, double y);

    /*
     람다구문
    (double x, double y) -> { return x + y; }
     */
}

package ch16.sec05.exam01;

public class Person {

    //함수형 인터페이스를 매개변수로 사용한 메소드
    public void action(Calcuable calcuable) {
        double result = calcuable.calc(10, 4);
        System.out.println("결과: " + result);
    }
}

package ch16.sec05.exam01;

public class Computer {
    //정적 메소드
    public static double staticMethod(double x, double y) {
        return x + y;
    }

    //인스턴스 메소드
    public double instanceMethod(double x, double y) {
        return x * y;
    }
}

package ch16.sec05.exam01;

public class MethodReferenceExample {

    public static void main(String[] args) {
        Person person = new Person();

        //매개변수에 람다식 구문을 값으로 제공.
        person.action((double x, double y) -> { return x + y; });

        //메소드 참조
        /* 리턴타입과 매개변수의 타입과 개수가 일치될 때 메소드 참조 문법을 사용할수가 있다.
         double calc(double x, double y);
         static double staticMethod(double x, double y)
         double instanceMethod(double x, double y)
         */

        //람다식 구문
//        person.action((x, y) -> {return Computer.staticMethod(x, y);});
        //메소드 참조 구문
        person.action(Computer :: staticMethod);

        Computer com = new Computer();
        //람다식 구문
//        person.action((x, y) -> {return com.instanceMethod(x, y);});
        //메소드 참조 구문
        person.action(com :: instanceMethod);
    }
}

매개변수의 메소드 참조

  • 람다식에서 제공되는 a 매개변수의 메소드를 호출해서 b 매개변수를 매개값으로 사용


    출처, 이것이 자바다


  • a의 클래스 이름 뒤에 :: 기호를 붙이고 메소드 이름을 기술


    출처, 이것이 자바다


package ch16.sec05.exam02;

@FunctionalInterface
public interface Comparable {
    int compare(String a, String b); //2개의 매개변수를 대소 비교하여 int결과값으로 표현. 

    /*
     람다식 구문
     (String a, String b) -> { return int형 값; }
     */
}

package ch16.sec05.exam02;

public class Person {

    //매개변수에 람다식 구문이 사용된다.
    public void ordering(Comparable comparable) {
        String a = "홍길동";
        String b = "김길동";

        int result = comparable.compare(a, b);

        if(result < 0) {
            System.out.println(a + "은" + b + "보다 앞에 옵니다.");
        }else if(result == 0) {
            System.out.println(a + "은" + b + "과 같습니다.");
        }else {
            System.out.println(a + "은" + b + "보다 뒤에 옵니다.");
        }
    }
}

package ch16.sec05.exam02;

public class MethodReferenceExample {

    public static void main(String[] args) {
        Person person = new Person();
        //람다식 구문
//        person.ordering((String a, String b) -> {return a.compareToIgnoreCase(b);});

        //첫번째 a변수의 메소드 호출시 매개변수값이 두번째(b변수)로 사용될 경우 매개변수의 메소드 참조 구문 사용가능

        //매개변수의 메소드 참조 구문
        person.ordering(String :: compareToIgnoreCase);
    }
}

package ch16.sec05.exam03;

@FunctionalInterface
public interface Creatable1 {
    public Member create(String id);
}

package ch16.sec05.exam03;

@FunctionalInterface
public interface Creatable2 {
    public Member create(String id, String name);
}

package ch16.sec05.exam03;

public class Member {

    private String id;
    private String name;

    public Member(String id) {
        this.id = id;
        System.out.println("Member(String id)");
    }

    public Member(String id, String name) {
        this.id = id;
        this.name = name;
        System.out.println("Member(String id, String name)");
    }

    @Override
    public String toString() {
        String info = "{id: " + id +", name: " + name + "}";
        return info;
    }
}

package ch16.sec05.exam03;

public class Person {
    public Member getMember1(Creatable1 creatable) {
        String id = "winter";
        Member member = creatable.create(id);
        return member;
    }

    public Member getMember2(Creatable2 creatable) {
        String id = "winter";
        String name = "한겨울";
        Member member = creatable.create(id, name);
        return member;
    }
}

package ch16.sec05.exam03;

public class ConstructorReferenceExample {

    public static void main(String[] args) {
        Person person = new Person();

        //람다식이 객체를 생성하고, 리턴하는 구문인 경우 생성자 참조 구문으로 사용가능.
//        Member m1 = person.getMember1((String id) -> {return new Member("winter");});

        //생성자 참조 구문
        Member m1 = person.getMember1(Member :: new);
        System.out.println(m1); //m1.toString();
        System.out.println();

//        Member m2 = person.getMember2((String id, String name) -> {return new Member("winter", "한겨울");});
        Member m2 = person.getMember2(Member :: new);
        System.out.println(m2); //m2.toString();
    }
}

'라이브러리 활용 - 람다식' 카테고리의 다른 글

생성자 참조  (0) 2023.02.07
람다식  (0) 2023.02.07