JAVA · 람다/메서드
함수형 인터페이스 합성
Function, Predicate, Consumer의 합성 메서드를 활용합니다.
람다/메서드중급FunctionPredicatecomposeandThen
핵심 설명
Function, Predicate, Consumer의 합성 메서드를 활용합니다.
Java code
import java.util.function.*;
public class FunctionComposition {
public static void main(String[] args) {
// Function 합성
Function<String, String> trim = String::trim;
Function<String, String> upper = String::toUpperCase;
Function<String, Integer> length = String::length;
// andThen: trim -> upper -> length
Function<String, Integer> pipeline =
trim.andThen(upper).andThen(length);
System.out.println(pipeline.apply(" hello ")); // 5
// compose: length(upper(trim(x))) — 역순
Function<String, String> step = upper.compose(trim);
System.out.println(step.apply(" hello ")); // HELLO
// Predicate 합성
Predicate<String> notEmpty = s -> !s.isEmpty();
Predicate<String> isShort = s -> s.length() < 10;
Predicate<String> valid = notEmpty.and(isShort);
System.out.println(valid.test("hi")); // true
System.out.println(valid.test("")); // false
// Consumer 합성
Consumer<String> print = System.out::println;
Consumer<String> log = s -> System.out.println("[LOG] " + s);
Consumer<String> both = print.andThen(log);
both.accept("테스트");
}
}학습 팁
andThen은 왼쪽→오른쪽 순서, compose는 오른쪽→왼쪽 순서입니다. 파이프라인에는 andThen이 직관적입니다.
주의할 점
compose와 andThen의 실행 순서를 혼동하면 예상과 다른 결과가 나옵니다. 항상 순서를 확인하세요.
자주 묻는 질문
함수형 인터페이스 합성란 무엇인가요?
Function , Predicate , Consumer 의 합성 메서드를 활용합니다.
함수형 인터페이스 합성 학습 시 주의할 점은 무엇인가요?
compose 와 andThen 의 실행 순서를 혼동하면 예상과 다른 결과가 나옵니다. 항상 순서를 확인하세요.
Continue Learning
Java 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.