[Java] 람다식 - Lambda Expression

혜 콩·2023년 4월 4일

Backend

목록 보기
3/9
post-thumbnail

람다식 (Lamda Expressions)

  • 메소드를 하나의 식 으로 표현한 것 = 한 줄 함수 (Java 8~)
  • 함수명 선언 X, 식별자없이 사용 가능한 함수
(매개변수, ...) -> {실행문 ...}


(x, int y) -> {x+y};                // example



🔔 함수형 인터페이스

  • Funtional Interface: 함수가 하나만 존재하는 인터페이스
@FunctionalInterface
interface Test {
    int Sub(int x, int y);
}

public class Calculate {
    public void cal(Test t) {
        int result = t.Sub(10, 3);
        System.out.println(result);
    }
}
// Lamda not used
public static void main(String[] args) {
        Calculate c = new Calculate();
        c.cal(new Test() {
            @Override    
            public int Sub(int x, int y) {        // Interface 구현
                System.out.println("Interface 구현: x= "+x+", y= "+y);    
                return (x-y);
            }
        });
    }

>>> Interface 구현: x= 10, y= 3
    7

=======================================================================

// Lamda used
public static void main(String[] args) {
        Calculate c = new Calculate();
        c.cal((x, y) -> {
            System.out.println("Interface 구현: x= "+x+", y= "+y);
            return (x-y);
        });


>>> Interface 구현: x= 10, y= 3
    7
profile
배우고 싶은게 많은 개발자📚

0개의 댓글