본문 바로가기
JAVA/Java Study

[Java] 람다 표현식(Lambda Expression)

by ♡˖GYURI˖♡ 2024. 6. 24.

람다 표현식

메서드를 하나의 식으로 표현한 것

  • 형태는 매개 변수를 가진 코드 블록이지만 런타임 시에는 익명 클래스를 생성
  • 간략하면서도 명확한 식으로 표현
  • 객체 지향보다 함수 지향 언어와 가까움
  • (타입 매개변수) → {실행문; ...} 형태로 작성
interface LambdaTest {
	int addOne(int i);
}

public class LambdaExample {
	public static void main(String[] args) {
    	LambdaTest test = i -> ++i;
        System.out.println(test.addOne(1));
    }
}

 

 

람다 표현식의 특징

장점

  • 코드의 간결성
  • 지연연산 수행
  • 병렬처리 가능

단점

  • 불필요한 사용 시, 가독성 저하
  • 람다식의 호출이 까다로움
  • 람다 stream으로 단순 반복문 사용 시 성능 저하

 

 

함수형 인터페이스

구현해야 할 추상 메소드가 하나만 정의된 인터페이스

  • 인터페이스 위에 @FunctionalInterface를 붙여 표시
  • 컴파일러에서 추상메서드를 갖춘 인터페이스인지 검사
@FunctionalInterface
public interface FunctionalInterfaceExample {
	void method();
}

 

 

java.util.function 패키지

자주 사용하는 형식에 대한 interface를 제공(≥ JDK 1.8)

Interface Function Descriptor Abstract method
Predicate<T> (T) → boolean boolean test(T t);
Consumer<T> (T) → void void accept(T t);
Function<T, R> (T) → R R apply(T t);
Supplier<T> () → T T get();
UnaryOperator<T> (T) → T T apply(T t);
import java.util.function.*;

public class OtherFunctionalInterfaceExample {
	public static void main(String[] args) {
    	Predicate<String> isEmptyString = String::isEmpty;
        Consumer<String> sentence = (str) -> System.out.println("+" + str);
        Function<String, Integer> strLength = (String s) -> s.length();
        Supplier<Long> currentTime = () -> System.currentTimeMillis();
        UnaryOperator<Integer> twoSum = (i) -> i + i;
        
        System.out.println(isEmptyString.test(""));
        sentence.accept("Consumer Class");
        System.out.println(strLength.apply("Function"));
        System.out.println(currentTime);
        System.out.println(twoSum.apply(123));
    }
}

 

 

P. 특정 수를 입력 받아 해당 수의 제곱과 루트를 구하는 람다 표현식 작성

Condition

  • Interface 정의
  • 하나의 메소드로 두 가지 기능 구현
public interface CalculateInterface<T> {
	T calculate(T t);
}
import java.util.*;

public class Problem {
	public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
        int powNum = sc.nextInt();
        CalculateInterface<Integer> pow = i -> i * i;
        System.out.println(pow.calculate(powNum);
        
        double sqrtNum = sc.nextDouble();
        CalculateInterface<Double> sqrt = i -> Math.sqrt(i);
        System.out.println(sqrt.calculate(sqrtNum));
    }
}