For more information about the collation service see the users guide.
Examples of use
// Get the Collator for US English and set its strength to PRIMARY Collator usCollator = Collator.getInstance(Locale.US); usCollator.setStrength(Collator.PRIMARY); if (usCollator.compare("abc", "ABC") == 0) { System.out.println("Strings are equivalent"); } The following example shows how to compare two strings using the Collator for the default locale. // Compare two strings in the default locale Collator myCollator = Collator.getInstance(); myCollator.setDecomposition(NO_DECOMPOSITION); if (myCollator.compare("à\u0325", "a\u0325̀") != 0) { System.out.println("à\u0325 is not equals to a\u0325̀ without decomposition"); myCollator.setDecomposition(CANONICAL_DECOMPOSITION); if (myCollator.compare("à\u0325", "a\u0325̀") != 0) { System.out.println("Error: à\u0325 should be equals to a\u0325̀ with decomposition"); } else { System.out.println("à\u0325 is equals to a\u0325̀ with decomposition"); } } else { System.out.println("Error: à\u0325 should be not equals to a\u0325̀ without decomposition"); }@see CollationKey @author Syn Wee Quek @stable ICU 2.8
You can set a Collator
's strength property to determine the level of difference considered significant in comparisons. Four strengths are provided: PRIMARY
, SECONDARY
, TERTIARY
, and IDENTICAL
. The exact assignment of strengths to language features is locale dependant. For example, in Czech, "e" and "f" are considered primary differences, while "e" and "ě" are secondary differences, "e" and "E" are tertiary differences and "e" and "e" are identical. The following shows how both case and accents could be ignored for US English.
//Get the Collator for US English and set its strength to PRIMARY Collator usCollator = Collator.getInstance(Locale.US); usCollator.setStrength(Collator.PRIMARY); if( usCollator.compare("abc", "ABC") == 0 ) { System.out.println("Strings are equivalent"); }
For comparing String
s exactly once, the compare
method provides the best performance. When sorting a list of String
s however, it is generally necessary to compare each String
multiple times. In this case, CollationKey
s provide better performance. The CollationKey
class converts a String
to a series of bits that can be compared bitwise against other CollationKey
s. A CollationKey
is created by a Collator
object for a given String
.
Note: CollationKey
s from different Collator
s can not be compared. See the class description for {@link CollationKey}for an example using CollationKey
s.
@see RuleBasedCollator
@see CollationKey
@see CollationElementIterator
@see Locale
@version 1.46, 07/23/06
@author Helena Shih, Laura Werner, Richard Gillam
|
|
|
|