Java 12 added a couple of useful APIs to the String class. In this tutorial, we will explore these new APIs with examples.
The indent() method adjusts the indentation of each line of the string based on the argument passed to it.
When indent() is called on a string, the following actions are taken:
For example:
@Test
public void whenPositiveArgument_thenReturnIndentedString() {
String multilineStr = "This is\na multiline\nstring.";
String outputStr = " This is\n a multiline\n string.\n";
String postIndent = multilineStr.indent(3);
assertThat(postIndent, equalTo(outputStr));
}
We can also pass a negative int to reduce the indentation of the string. For example:
@Test
public void whenNegativeArgument_thenReturnReducedIndentedString() {
String multilineStr = " This is\n a multiline\n string.";
String outputStr = " This is\n a multiline\n string.\n";
String postIndent = multilineStr.indent(-2);
assertThat(postIndent, equalTo(outputStr));
}
We can apply a function to this string using the transform() method. The function should expect a single String argument and produce a result:
@Test
public void whenTransformUsingLamda_thenReturnTransformedString() {
String result = "hello".transform(input -> input + " world!");
assertThat(result, equalTo("hello world!"));
}
It is not necessary that the output has to be a string. For example:
@Test
public void whenTransformUsingParseInt_thenReturnInt() {
int result = "42".transform(Integer::parseInt);
assertThat(result, equalTo(42));
}
In this article, we explored the new String APIs in Java 12. As usual, code snippets can be found over on GitHub.
#java #string