What is better word.toUpperCase().chars() or word.chars().map(Chars::toUpperCase)?

Viewed 104

We need to get characters stream from string in upper case. There are two approaches:

  1. word.toUpperCase().chars()

  2. word.chars().map(Character::toUpperCase)

Which approach is better?

P.S. as requested in comments I specify the whole method where the code is used:

private int[] toSortedChars(final String word) {
   return word.chars().map(Character::toLowerCase).sorted().toArray();
}

The method is used to solve the exercise: https://exercism.org/tracks/java/exercises/anagram

1 Answers

The first method is better.

The Javadoc of Character.toUpperCase mentions:

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.

You may not be thinking about different languages than English right now, but at some point you might want to support other languages, and then capitalization becomes more difficult because characters cannot be capitalized on their own any more.

For example: "Straße".toUpperCase() returns "STRASSE" (even in English locales), which is behaviour that you cannot replicate if you are converting each character to upper case separately.

(Note: Recently, an uppercase "ß" was added to the German language, but it's not frequently used yet, except in capitalized names.)

Related