«1. Введение

В Java 12 к классу String добавлено несколько полезных API. В этом руководстве мы рассмотрим эти новые API на примерах.

2. indent()

Метод indent() корректирует отступ каждой строки строки на основе переданного ему аргумента.

Когда indent() вызывается для строки, выполняются следующие действия:

  1. The string is conceptually separated into lines using lines(). lines() is the String API introduced in Java 11.
  2. Each line is then adjusted based on the int argument n passed to it and then suffixed with a line feed “\n”.
    1. If n > 0, then n spaces are inserted at the beginning of each line.
    2. If n < 0, then up to n white space characters are removed from the beginning of each line. In case a given line does not contain sufficient white space, then all leading white space characters are removed.
    3. If n == 0, then the line remains unchanged. However, line terminators are still normalized.
  3. The resulting lines are then concatenated and returned.

Например:

@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));
}

Мы также можем передать отрицательное значение int, чтобы уменьшить отступ строки. Например:

@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));
}

3. transform()

Мы можем применить функцию к этой строке, используя метод transform(). Функция должна ожидать один аргумент String и выдавать результат:

@Test
public void whenTransformUsingLamda_thenReturnTransformedString() {
    String result = "hello".transform(input -> input + " world!");

    assertThat(result, equalTo("hello world!"));
}

Нет необходимости, чтобы вывод был строкой. Например:

@Test
public void whenTransformUsingParseInt_thenReturnInt() {
    int result = "42".transform(Integer::parseInt);

    assertThat(result, equalTo(42));
}

4. Заключение

В этой статье мы рассмотрели новые API-интерфейсы String в Java 12. Как обычно, фрагменты кода можно найти на GitHub.