Java 11文字列APIの追加
1. 前書き
Java 11は、一般的に使用されるString classにいくつかの便利なAPIを追加しました。 このチュートリアルでは、これらの新しいAPIを調べて使用します。
2. repeat()
名前が示すように、repeat()インスタンスメソッドは文字列の内容を繰り返します。
It returns a string whose value is the concatenation of the string repeated n times, where n is passed as a parameter:
@Test
public void whenRepeatStringTwice_thenGetStringTwice() {
String output = "La ".repeat(2) + "Land";
is(output).equals("La La Land");
}
さらに、文字列が空の場合、またはカウントがゼロの場合、repeat()は空の文字列を返します。
3. strip()*
The strip() instance method returns a string with all leading and trailing whitespaces removed:
@Test
public void whenStripString_thenReturnStringWithoutWhitespaces() {
is("\n\t hello \u2005".strip()).equals("hello");
}
Java 11では、先頭と末尾の空白をそれぞれ処理するメソッドstripLeading()とstripTrailing()も追加されました。
3.1. strip()とtrim()の違い
strip*()は、Character.isWhitespace()に基づいて、文字が空白であるかどうかを判別します。 つまり、it is aware of Unicode whitespace charactersです。
これは、スペースをUnicodeスペース文字(U + 0020)以下の任意の文字として定義するtrim()とは異なります。 前の例でtrim()を使用すると、異なる結果が得られます。
@Test
public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() {
is("\n\t hello \u2005".trim()).equals("hello \u2005");
}
trim()が先頭の空白を削除できたが、末尾の空白は削除されなかったことに注意してください。 これは、trim()がUnicode空白文字を認識しないため、 ‘ ′が空白文字と見なされないためです。
4. isBlank()
The isBlank() instance method returns true if the string is empty or contains only whitespace. Otherwise, it returns false:
@Test
public void whenBlankString_thenReturnTrue() {
assertTrue("\n\t\u2005 ".isBlank());
}
同様に、isBlank()メソッドは、strip()と同様に、Unicode空白文字を認識します。
5. lines()
The lines() instance method returns a Stream of lines extracted from the string, separated by line terminators:
@Test
public void whenMultilineString_thenReturnNonEmptyLineCount() {
String multilineStr = "This is\n \n a multiline\n string.";
long lineCount = multilineStr.lines()
.filter(String::isBlank)
.count();
is(lineCount).equals(3L);
}
ラインターミネータは、“ ”,“ ”,または“ ”のいずれかです。
ストリームには、発生順に行が含まれます。 ラインターミネータは各ラインから削除されます。
この方法は、複数行の入力を中断するためのパフォーマンスが向上するため、split()よりも優先する必要があります。
6. 結論
この簡単な記事では、Java 11の新しいString APIについて説明しました。
最後に、コードスニペットはover on GitHubにあります。