Skip to content

Instantly share code, notes, and snippets.

@boukadam
Last active May 29, 2021 18:16
Show Gist options
  • Save boukadam/6fc1eca7658765732d37e5da166fc3f6 to your computer and use it in GitHub Desktop.
Save boukadam/6fc1eca7658765732d37e5da166fc3f6 to your computer and use it in GitHub Desktop.
Java - Indent a string by curly braces
public static String indent(String expression) {
List<String> strings = Stream.of(expression)
.map(e -> e.replace("{", "{#"))
.map(e -> e.replace("}", "#}#"))
.flatMap(e -> Arrays.stream(e.split("[#\\n]")))
.map(String::trim)
.filter(e -> !e.isEmpty())
.collect(Collectors.toList());
var indent = 0;
StringBuilder sb = new StringBuilder();
for (String string : strings) {
if (string.equals("}")) {
indent--;
}
sb.append(" ".repeat(indent)).append(string).append("\n");
if (string.indexOf('{') != -1) {
indent ++;
}
}
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment