람다 표현식은 Java 8 에 추가된 기능으로
매개변수를 받아서 값을 반환하는 짧은 코드 블록이다.
람다 표현식을 사용하면 간결하고 가독성 높은 코드를 작성할 수 있으며,
함수형 프로그래밍의 핵심 요소로 , 함수형 인터페이스와 함께 사용된다.
() -> {표현식
Runnable r = () -> { System.out.println("Hello, Lambda!"); };
(매개변수) -> {표현식}
Consumer<String> printer = message -> System.out.println(message);
(매개변수1, 매개변수2) -> {표현식}
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
(매개변수) -> { return value;}
// return 생략 가능
Function<Integer, Integer> square = x -> x * x;
Predicate<Integer> isPositive = n -> n > 0;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(3);
numbers.forEach(n -> System.out.println(n));
}
}
import java.util.function.BiFunction;
public class Main {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(5, 10)); // 출력: 15
}
}
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<Integer> isEven = n -> n % 2 == 0;
System.out.println(isEven.test(4)); // true
System.out.println(isEven.test(5)); // false
}
}
Function<Integer, Integer> square = x -> x * x; // 매개변수 x의 타입은 Integer로 추론
// 반환값 있음 (return 생략)
Function<String, Integer> length = str -> str.length();
// 반환값 있음 (return 명시)
Function<Integer, String> evenOdd = n -> {
if (n % 2 == 0) return "Even";
else return "Odd";
};
@FunctionalInterface
interface MyFunc {
void apply(int x, int y); // 단일 추상 메서드
}
public class Main {
public static void main(String[] args) {
// 람다 표현식으로 함수형 인터페이스 구현
MyFunc add = (a, b) -> { System.out.println(a + b); };
// apply 메서드 호출
add.apply(5, 10); // 출력: 15
}
}
| 인터페이스 | 설명 | 메서드 | 예시 람다 형태 |
|---|---|---|---|
Consumer<T> | 매개변수를 받아 소비(출력 등) | accept(T t) | (n) -> System.out.println(n) |
Function<T, R> | 입력값을 받아 반환값을 생성 | apply(T t) | (x) -> x * x |
Predicate<T> | 입력값을 평가(참/거짓 반환) | test(T t) | (x) -> x > 10 |
Supplier<T> | 값을 반환 | get() | () -> "Hello" |