word.toUpperCase().chars() 或 word.chars().map(Chars::toUpperCase) 哪个更好?
What is better word.toUpperCase().chars() or word.chars().map(Chars::toUpperCase)?
我们需要从大写字符串中获取字符流。有两种方法:
word.toUpperCase().chars()
word.chars().map(Character::toUpperCase)
哪种方法更好?
P.S。按照评论中的要求,我指定了使用代码的整个方法:
private int[] toSortedChars(final String word) {
return word.chars().map(Character::toLowerCase).sorted().toArray();
}
解决习题所用的方法:
https://exercism.org/tracks/java/exercises/anagram
第一种方法更好
Character.toUpperCase 的 Javadoc 提到:
In general, String.toUpperCase() should be used to map characters to uppercase. String case mapping methods have several benefits over Character case mapping methods. String case mapping methods can perform locale-sensitive mappings, context-sensitive mappings, and 1:M character mappings, whereas the Character case mapping methods cannot.
您现在可能没有考虑除英语之外的其他语言,但在某些时候您可能想要支持其他语言,然后大写变得更加困难,因为字符不能再单独大写。
例如:"Straße".toUpperCase()
returns "STRASSE"
(即使在英语语言环境中),如果您将每个字符分别转换为大写,则无法复制这种行为。
(注意:最近,德语中增加了一个大写的“ß”,但目前还不常用,除了大写的名字。)
我们需要从大写字符串中获取字符流。有两种方法:
word.toUpperCase().chars()
word.chars().map(Character::toUpperCase)
哪种方法更好?
P.S。按照评论中的要求,我指定了使用代码的整个方法:
private int[] toSortedChars(final String word) {
return word.chars().map(Character::toLowerCase).sorted().toArray();
}
解决习题所用的方法: https://exercism.org/tracks/java/exercises/anagram
第一种方法更好
Character.toUpperCase 的 Javadoc 提到:
In general, String.toUpperCase() should be used to map characters to uppercase. String case mapping methods have several benefits over Character case mapping methods. String case mapping methods can perform locale-sensitive mappings, context-sensitive mappings, and 1:M character mappings, whereas the Character case mapping methods cannot.
您现在可能没有考虑除英语之外的其他语言,但在某些时候您可能想要支持其他语言,然后大写变得更加困难,因为字符不能再单独大写。
例如:"Straße".toUpperCase()
returns "STRASSE"
(即使在英语语言环境中),如果您将每个字符分别转换为大写,则无法复制这种行为。
(注意:最近,德语中增加了一个大写的“ß”,但目前还不常用,除了大写的名字。)