JAVA · 함수형/Stream
함수 합성과 파이프라인
여러 함수를 합성하여 데이터 변환 파이프라인을 구축합니다.
함수형/Stream고급함수합성PipelineandThencompose
핵심 설명
여러 함수를 합성하여 데이터 변환 파이프라인을 구축합니다.
Java code
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class FunctionPipeline {
// 파이프라인 빌더
static class Pipeline<T> {
private final List<Function<T, T>> steps = new ArrayList<>();
Pipeline<T> addStep(Function<T, T> step) {
steps.add(step);
return this;
}
Function<T, T> build() {
return steps.stream()
.reduce(Function.identity(), Function::andThen);
}
}
public static void main(String[] args) {
// 문자열 처리 파이프라인
Pipeline<String> textPipeline = new Pipeline<String>()
.addStep(String::trim)
.addStep(String::toLowerCase)
.addStep(s -> s.replaceAll("[^a-z0-9 ]", ""))
.addStep(s -> s.replaceAll("\\s+", "-"));
Function<String, String> slugify = textPipeline.build();
System.out.println(slugify.apply(" Hello, World! 123 "));
// hello-world-123
// 숫자 변환 파이프라인
Function<Integer, Integer> mathPipe =
((Function<Integer, Integer>) n -> n * 2)
.andThen(n -> n + 10)
.andThen(n -> n * n);
System.out.println(mathPipe.apply(5)); // (5*2+10)^2 = 400
// 검증 파이프라인
List<Predicate<String>> validators = List.of(
s -> !s.isEmpty(),
s -> s.length() <= 50,
s -> s.matches("[a-zA-Z0-9 ]+")
);
Predicate<String> allValid = validators.stream()
.reduce(Predicate::and)
.orElse(s -> true);
System.out.println(allValid.test("Hello123")); // true
System.out.println(allValid.test("")); // false
}
}학습 팁
Function.identity()는 항등 함수로, reduce의 초기값으로 사용하면 빈 파이프라인도 안전하게 처리됩니다.
주의할 점
함수 합성 순서를 혼동하지 마세요. f.andThen(g)는 f를 먼저 적용하고, f.compose(g)는 g를 먼저 적용합니다.
자주 묻는 질문
함수 합성과 파이프라인란 무엇인가요?
여러 함수를 합성하여 데이터 변환 파이프라인을 구축합니다.
함수 합성과 파이프라인 학습 시 주의할 점은 무엇인가요?
함수 합성 순서를 혼동하지 마세요. f.andThen(g) 는 f를 먼저 적용하고, f.compose(g) 는 g를 먼저 적용합니다.
Continue Learning
Java 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.