본문 바로가기

Java

람다 lambda

  • 자바 8부터 지원하는 함수 구현과 호출 만으로 프로그래밍 하는 함수형 프로그래밍 방식 지원
  • 이름이 없는 익명 함수
  • 함수적 인터페이스로 구현
  • Kotlin, Scala 같은 언어도 객체지향 + 함수형 언어

람다식 형식

  • 타입 생략 가능
  • 매개변수가 한개라면 괄호도 생략 가능
  • 매개변수가 없는 경우는 괄호 생략 불가
  • 실행문이 한개라면 중괄호도 생략 가능
(타입 매개변수...) -> {
    실행문 ..
}

() -> {}
package chapter15;

public class LambdaFunctionEx {

    public static void main(String[] args) {

                // 람다식
        InterfaceEx ie = (int x, int y) -> x+y;

        System.out.println(ie.sum(1, 2));

    }

}

// 함수적 인터페이스
interface InterfaceEx {
    public int sum(int x, int y);
}

함수적 인터페이스

  • 함수는 하나의 추상메서드만 정의하는 인터페이스
  • 람다식이 추상메서드를 재정의 하는 개념
  • 대표적으로 Runnable 인터페이스 run() 추상메서드 하나 정의 되어 있음
package chapter15;

public class LambdaEx {

    public static void main(String[] args) {

        LambdaInterface li = () -> {
            String str = "메서드 출력";
            System.out.println(str);
        };

        li.print();

    }

}

interface LambdaInterface {
    void print();
    //void print2(); // 오류발생
}

@FunctionalInterface

  • 2개이상 메서드 선언시 오류 체크
package chapter15;

public class LambdaEx3 {

    public static void main(String[] args) {

        LambdaInterface3 li3 = (String name) -> {
            System.out.println("제 이름은 "+name+"입니다.");
        };

        li3.print("홍길동");

    }

}

@FunctionalInterface
interface LambdaInterface3 {
    void print(String name);
}

매개변수와 리턴값 사용

package chapter15;

public class LambdaEx4 {

    public static void main(String[] args) {

        LambdaInterface4 f4 = (x,y) -> {
            return x * y;
        };
        System.out.println("두 수의 곱 : " + f4.cal(3, 2));

        f4 = (x, y) -> x + y;
        System.out.println("두 수의 합 : " + f4.cal(3, 2));

        f4 = (x, y) -> { return x/y; };
        System.out.println("두 수의 몫 : " + f4.cal(5, 2));

        f4 = (x, y) -> x%y;
        System.out.println("두 수의 나머지 : " + f4.cal(5, 2));

        f4 = (x,y) -> sum(x, y);
        System.out.println("두 수의 합(sum()) : " + f4.cal(3, 2));

    }

    static int sum(int x, int y) {
        return x+y;
    }

}

@FunctionalInterface
interface LambdaInterface4 {
    int cal(int x, int y);
}

다양한 함수적 인터페이스

  • 다양한 함수적 인터페이스가 있으며 필요 시 추가 학습
  • 최근의 프로그래밍 언어에서는 배열이나 List의 데이터들을 변경하기 위해 map, filter, reduce 메서드 제공됨
  • 자바에서는 스트림 API에서 람다를 매개변수로 받아서 처리

'Java' 카테고리의 다른 글

스레드 thread  (0) 2022.03.07
스트림 stream  (0) 2022.03.07
제네릭 generic  (0) 2022.03.07
컬렉션 F/W collection  (0) 2022.03.07
java api  (0) 2022.03.07