String transform Chained Functions
String.transform applies a function to the string and returns its result, so multi-step text pipelines read in order without nested call nesting.
Code
import java.util.Locale;
public class TransformPipeline {
public static void main(String[] args) {
String raw = " user Input Field ";
// transform(JDK 12+):把函数应用到字符串,返回函数结果
// 链式书写与执行顺序一致:strip -> lower -> 空格换连字符
String slug = raw
.transform(String::strip)
.transform(s -> s.toLowerCase(Locale.ROOT))
.transform(s -> s.replace(' ', '-'));
System.out.println("slug: " + slug);
// 返回类型不必是 String:transform 可收尾成任意类型
int wordCount = raw.transform(String::strip)
.transform(s -> s.split("\\s+"))
.transform(parts -> parts.length);
System.out.println("words: " + wordCount);
// 对比嵌套调用:内层先执行,读起来是反的
String nested = raw.strip().toLowerCase(Locale.ROOT).replace(' ', '-');
System.out.println("same: " + slug.equals(nested));
}
}How it works
The moving parts are the class TransformPipeline and the function main.
What to watch for
- The toolchain by itself is enough — no dependency resolution runs.
Using it
The signature doing the main work is public static void main(String[] args)
Each step the file takes is announced in the output: slug:, words:, same:.
The key statements that remain
String nested = raw.strip().toLowerCase(Locale.ROOT).replace(' ', '-');
int wordCount = raw.transform(String::strip)
.transform(s -> s.split("\\s+"))
.transform(parts -> parts.length);
.transform(s -> s.toLowerCase(Locale.ROOT))
.transform(s -> s.replace(' ', '-'));
Interactive Tools for This Topic
FAQ
- What does String transform Chained Functions print when run?
- Run it as a complete program — the output lines carry labels such as `slug:`, `words:`, `same:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.