Strings beginner

String.indent() and transform()

Indent text and chain string transformations fluently.

✕ Java 8
String[] lines = text.split("\n");
StringBuilder sb = new StringBuilder();
for (String line : lines) {
    sb.append("    ").append(line)
      .append("\n");
}
String indented = sb.toString();
✓ Java 12+
String indented = text.indent(4);

String result = text
    .transform(String::strip)
    .transform(s -> s.replace(" ", "-"));
📏

Built-in

Indentation is a common operation — now it's one call.

🔗

Chainable

transform() enables fluent pipelines on strings.

🧹

Clean code

No manual line splitting and StringBuilder loops.

Old Approach
Manual Indentation
Modern Approach
indent() / transform()
Since JDK
12
Difficulty
beginner
String.indent() and transform()
Available

Widely available since JDK 12 (March 2019)

How it works

indent(n) adds n spaces to each line. transform(fn) applies any function and returns the result, enabling fluent chaining of string operations.

Share 𝕏 🦋 in