람다

이규은·2021년 11월 3일
1

람다

목록 보기
1/1

람다식 사용법

(매개변수, ...) -> {실해문}

매개변수는 오른쪽 중괄호 블록을 실행하기 위해 필요한 값을 제공하는 역할을 한다.
매개변수의 이름은 자유롭게 지정할수 있고 인자타입을 명시하지 않아도 된다.
-> 기호는 매개 변수를 이용해 중괄호를 실행한다는 뜻이다.

@FunctionalInterface
interface Say {
    int something(int a, int b);
}

class Person {
    public void hi(Say line) {
        int number = line.something(3, 4);
        System.out.println("number " + number);
    }
}


public class LambdaStudy {
    public static void main(String[] args) {
        Person person = new Person();
        person.hi((a, b) -> {
            System.out.println("number " + a + "," + b);
            return 7;
        });
    }
}

함수형 인터페이스

함수형 인터페이스란 1개의 추상 메소드를 갖는 인터페이스를 말한다.
여러개의 디폴트 메서드가 있더라도 추상 메서드가 오직 하나면 함수형 인터페이스이다.
자바의 람다 표현식은 함수형 인터페이로만 사용가능하다.

@FunctionalInterface
interface CustomInterface<T> {
    T myCall();

    default void printDefault() {
        System.out.println("Default");
    }

    static void printStatic() {
        System.out.println("Static");
    }
}


public class LambdaStudy {
    public static void main(String[] args) {
        CustomInterface<String> customInterface = () -> "Hello";

        String s = customInterface.myCall();
        System.out.println("s = " + s);

        customInterface.printDefault();
        CustomInterface.printStatic();
    }
}

java 에서 기본적으로 제공하는 Functional Interfaces

함수형 인터페이스 Descripter Method
Predicate T -> boolean boolean test(T t)
Consumer T -> void void accept(T t)
Supplier () -> T T get()
Function<T, R> T -> R R apply(T t)
Comparator (T, T) -> int int compare(T o1, T 02)
Runnable () -> void void run()
Callable () -> T V call()

Variable Capture

람다 시그니처 파라미터로 넘겨전 변수가 아닌 외부에서 정의된 변수를 자유 변수 라고 부른다.
람다 바디에서 자유 변수를 참조하는 행위를 람다 캡처링 이라고 부른다.

람다 캡처링의 제약 조건

  1. 지역변수는 final로 선언돼있어야한다.
  2. final로 선언되지 않은 지역변수는 final처럼 동작해야 한다.

메소드 참조

메소드 참조는 메소드를 간결하게 지칭할 수 있는 방법으로 람다가 쓰이는 곳 어디서나 사용할수 있다.
이미 존재하는 이름을 가진 메소드를 람다로써 사용할수 있도록 참조하는 역할을 한다.

@FunctionalInterface
interface Conversion {
    String convert(Integer integer);
}

public class LambdaMethod {
    public static String convert(Integer integer, Conversion conversion) {
        return conversion.convert(integer);
    }
    public static void main(String[] args) {
        convert(100, (integer -> String.valueOf(integer)));
        convert(100, String::valueOf);
    }
}

생성자 참조

생성자를 호출해서 인스턴스를 생성하는 것이 아닌 생성자 메소드를 참조하는 것이다.

String::new
() -> new String()
profile
안녕하세요

0개의 댓글