[Java와 Spring] 람다

개발log·2024년 4월 2일

자바와 스프링

목록 보기
9/10
post-thumbnail

람다

public class B002 {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                System.out.println("Hello Lambda 2!!!");
            }
        };
        r.run();
    }
}
public class B002 {
    public static void main(String[] args) {
        Runnable r = () -> {
        	System.out.println("Hello Lambda~!")
        };
        
        r.run();
	}
}

new Runnable() - 삭제

  • Runnalbe 타입으로 참조 변수 r을 만들고 있어 new Runnalbe()은 컴파일러가 알아낼 수 있기 때문에 삭제

public void run() → ()

  • Runnable 인터페이스가 가진 추상 메서드가 run() 메서드 단 하나이기 때문에 변경

'->' - 추가

  • 람다의 구조는 (인자 목록) -> {로직}
  • 단 한 줄로 표기되는 경우 블록 기호 {} 생략 가능

함수형 인터페이스

  • 함수형 인터페이스는 추상 메서드를 하나만 갖는 인터페이스를 뜻한다.(자바 8부터)
  • 함수형 인터페이스만을 람다식으로 변경할 수 있다.
public class B005 {
    public static void main(String[] args) {
        MyFunctionalInterface mfi = (int a) -> { return a + a; };

        int b = mfi.runSomething(5);

        System.out.println(b);
    }
}

@FunctionalInterface
interface MyFunctionalInterface {
    public abstract int runSomething(int count);
}

@FunctionalInterface 어노테이션

컴파일러는 해당 인터페이스가 함수형 인터페이스의 조건에 맞는지 검사(하나의 추상 메서드만을 갖고 있는지 확인)


메서드 호출 인자로 람다 사용

람다식을 메서드의 인자로도 사용 가능 - 코드 블록을 메서드의 인자로 전달
람다식을 단 한번만 사용한다면 변수에 할당할 이유가 없다.


메서드 반환값으로 람다 사용

public class B009 {
    public static void main(String[] args) {
        MyFunctionalInterface mfi = todo();

        int result = mfi.runSomething(3);

        System.out.println(result);
    }

    public static MyFunctionalInterface todo() {
        return num -> num * num;
    }
}

자바 8 API에서 제공하는 함수형 인터페이스

함수형 인터페이스추상 메서드용도
Runnablevoid run()실행 할 수 있는 인터페이스
SupplierT get()제공 할 수 있는 인터페이스
Consumervoid accept(T t)소비 할 수 있는 인터페이스
Function<T, R>R apply(T t)입력을 받아서 출력 할 수 있는 인터페이스
PredicateBoolean test(T t)입력을 받아 참/거짓을 단정 할 수 있는 인터페이스
UnaryOperatorT apply(T t)단항(Unary) 연산 할 수 있는 인터페이스
BiConsumer<T, U>void accept(T t, U u)이항 소비자 인터페이스
BiFunction<T, U, R>R apply(T t, U u)이항 함수 인터페이스
BiPredicate<T, U>Boolean test(T t, U u)이항 단정 인터페이스
BinaryOperator<T, T>T apply(T t, T t)이항 연산 인터페이스
profile
나의 개발 저장소

0개의 댓글