Programming/Java

[자바/Java] lambda 개념 및 사용법

코딩하는 랄로 2023. 10. 14. 20:44
반응형

람다(lambda)란

람다 함수는 프로그래밍 언어에서 사용되는 개념으로 익명 함수(Anonymous functions)를 뜻하는 말이다. 여기서 람다는 수학과기초 컴퓨터 과학 분야에서의 람다 대수에서 나온 용어로, 함수를 보다 단순하게 표현하는 방법을 뜻한다.

 

Lambda
=
프로그래밍적 동작을 보다 간단하게 표현한 이름 없는 함수

 

자바에서 람다 표현식(lambda-expression)은 Java8부터 도입된 개념이다. 람다 표현식은 추상 메소드가 하나뿐인 인터페이스를 구현하는 것이다. 그렇기 때문에 또 다른 말로, 함수형 인터페이스(functional interface)라고도 한다. 

 

익명 함수라는 말에서 알 수 있듯이 익명 클래스를 더 간략화한 표현식(메소드 한개를 표현하기 위한 식)이라고 이해하면 더 쉽게 이해할 수 있다.

 

 

 

람다의 장단점

장점

  • 코드의 간결성 : 람다를 사용하면 불필요한 반복문의 삭제가 가능하며 복잡한 식을 단순하게 표현
  • 지연연산 수행 - 람다는 지연연상을 수행 함으로써 불필요한 연산을 최소화 
  • 병렬처리 가능 - 멀티쓰레디를 활용하여 병렬처리

 

단점

  • 람다식의 호출이 까다로움
  • 람다 stream 사용 시 단순 for문 혹은 while문 사용 시 성능 저하
  • 불필요하게 너무 사용하게 되면 오히려 가독성 저하

 

 

 

람다 사용법

람다를 사용하는 법은 아래와 같다.

  • 람다는 (매개변수1, 매개변수2) -> { 함수 몸체 } 를 통해 사용
  • 매개변수가 없어도 소괄호는 표시해주어야 한다.
  • 매개변수의 타입은 생략 가능 -> 생략할 경우, 모든 매개변수의 타입을 생략해야 함
  • 함수 몸체가 단일 실행문이면 중괄호 생략 가능
  • 함수 몸체가 return문으로만 구성되어 있는 경우에도 중괄호 생략 가능

 

 

 

사용 예제1

// 함수형 인터페이스 정의
@FunctionalInterface
interface  Addable {
    double add(double x, double y);
}

//인터페이스를 구현하는 클래스를 정의
class AdderImple implements Addable {
    @Override
    public double add(double x, double y) {
       return x + y;
    }
}

public class Main {

    public static void main(String[] args) {

       // 함수형 인터페이스 사용
       Addable myAdder = new AdderImple();
       double result = myAdder.add(1.11, 2.22);
       System.out.println("result = " + result);
             

       // 람다를 사용하지 않은 익명 클래스
       Addable myAdder2 = new Addable() {
          @Override
          public double add(double x, double y) {
             return x + y;
          }
       };
       result = myAdder2.add(1.11, 2.22);
       System.out.println("result = " + result);
       
       //람다를 사용하여 표현
       Addable myAdder3 = (a, b) -> a + b;
       result = myAdder3.add(1.11, 2.22);
       System.out.println("result = " + result);

    } 
    
}

 

 

 

사용 예제2

@FunctionalInterface
interface Test01 {void testPrint();} 
@FunctionalInterface
interface Test02 {void testPrint(int num);} 
@FunctionalInterface
interface Test03 {int max(int n1, int n2);} 
@FunctionalInterface
interface Test04 {int myStrLen(String str);}
@FunctionalInterface
interface Test05 {void printMax(double x, double y);}

public class Main {

    public static void main(String[] args) {
  
       Test01 test1 = () -> System.out.println("Hello");
       test1.testPrint();
       
       Test02 test2 = x -> System.out.println(x);
       test2.testPrint(7);
       
       Test03 test3 = (x, y) -> (x > y) ? x : y;
       System.out.println("result = " + test3.max(10, 20));
	   //매개변수 타입 표현
       test3 = (int x, int y) -> (x > y) ? x : y;

       Test04 test4 = x -> {
          System.out.println(x);
          return x.length();
       };
       System.out.println("result = " + test4.myStrLen("코딩하는 랄로"));
       
       Test05 test5 = (x, y) -> {
          System.out.println("x = " + x);
          System.out.println("y = " + y);

          if (x > y) {
             System.out.println(x + " > " + y);
          } else {
             System.out.println(x + " <= " + y);
          }
       };
       test5.printMax(3.14, 1.2);
    } 
}

 

반응형