JAVA · 람다/메서드
람다 & 함수형 인터페이스
Java 8의 람다 표현식과 java.util.function 패키지의 함수형 인터페이스를 마스터합니다.
람다/메서드중급lambdaFunctionPredicateConsumerSupplier
핵심 설명
Java 8의 람다 표현식과 java.util.function 패키지의 함수형 인터페이스를 마스터합니다.
Java code
import java.util.function.*;
public class Lambdas {
public static void main(String[] args) {
// 기본 람다
Runnable r = () -> System.out.println("실행!");
r.run();
// Function<T, R> — T 입력, R 출력
Function<String, Integer> strLen = String::length;
Function<Integer, Integer> double_ = n -> n * 2;
Function<String, Integer> composed = strLen.andThen(double_);
System.out.println(composed.apply("Hello")); // 10
// Predicate<T> — boolean 반환
Predicate<String> notEmpty = s -> !s.isEmpty();
Predicate<String> longStr = s -> s.length() > 5;
Predicate<String> both = notEmpty.and(longStr);
System.out.println(both.test("Hello World")); // true
// Consumer<T> — 반환 없음
Consumer<String> print = System.out::println;
Consumer<String> printUpper = s -> System.out.println(s.toUpperCase());
print.andThen(printUpper).accept("java");
// Supplier<T> — 인자 없음
Supplier<String> greeting = () -> "Hello, Java!";
System.out.println(greeting.get());
// BiFunction<T, U, R>
BiFunction<Integer, Integer, Integer> add = Integer::sum;
System.out.println(add.apply(3, 4)); // 7
// UnaryOperator, BinaryOperator
UnaryOperator<Integer> square = n -> n * n;
BinaryOperator<Integer> multiply = (a, b) -> a * b;
System.out.println(square.apply(5)); // 25
System.out.println(multiply.apply(3,4)); // 12
}
}학습 팁
Function.andThen()은 왼쪽에서 오른쪽으로, Function.compose()는 오른쪽에서 왼쪽으로 합성합니다. 수학의 함수 합성과 반대 방향인 andThen이 더 직관적입니다.
주의할 점
람다에서 외부 변수를 캡처하려면 해당 변수가 effectively final이어야 합니다. 람다 외부에서 변수를 재할당하면 컴파일 에러가 납니다.
자주 묻는 질문
람다 & 함수형 인터페이스란 무엇인가요?
Java 8의 람다 표현식과 java.util.function 패키지의 함수형 인터페이스를 마스터합니다.
람다 & 함수형 인터페이스 학습 시 주의할 점은 무엇인가요?
람다에서 외부 변수를 캡처하려면 해당 변수가 effectively final이어야 합니다. 람다 외부에서 변수를 재할당하면 컴파일 에러가 납니다.
Continue Learning
Java 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.