java / intermediate
Snippet
Functional Pipeline Composition in Spring Services
Higher-order functional composition using java.util.function.Function and andThen() allows combining discrete transformation functions into a modular, reusable execution pipeline within a Spring bean.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Servicepublic class TextSanitizerService {private final Function<String, String> sanitizationPipeline;public TextSanitizerService() {Function<String, String> trimWhitespace = String::strip;Function<String, String> removeHtml = text -> text.replaceAll("<[^>]*>", "");Function<String, String> normalizeEscapes = text -> text.replace("\t", " ");this.sanitizationPipeline = trimWhitespace.andThen(removeHtml).andThen(normalizeEscapes);}public String sanitize(String rawInput) {return Optional.ofNullable(rawInput).map(sanitizationPipeline).orElse("");}}
spring
Breakdown
1
private final Function<String, String> sanitizationPipeline;
Stores a first-class function representing the composed processing chain.
2
this.sanitizationPipeline = trimWhitespace.andThen(removeHtml).andThen(normalizeEscapes);
Composes several discrete functions sequentially using andThen().
3
.map(sanitizationPipeline)
Applies the functional pipeline cleanly over optional data without manual null checking.